Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3.  
  4. public class CheckForBST {
  5.  
  6. // function to find out the inorder traversal of the tree.
  7. private static void inOrder(BinaryTreeNode root, ArrayList<Integer> list){
  8. if(root == null)
  9. return;
  10. inOrder(root.left, list);
  11. list.add(root.data);
  12. inOrder(root.right, list);
  13. }
  14.  
  15. // function to find out the inorder traversal of the tree.
  16. private static boolean isBST(BinaryTreeNode root){
  17. ArrayList<Integer> list = new ArrayList<>();
  18. inOrder(root, list);
  19.  
  20. // In java you can check if the arrayList is sorted or not in foll way.
  21. ArrayList<Integer> sortedList = (ArrayList<Integer>) list.clone();
  22. Collections.sort(sortedList);
  23.  
  24. return list.equals(sortedList);
  25. }
  26.  
  27. public static void main(String[] args) {
  28. // Line -32,33 is just to take input of binary tree from user. You can use your own method to take input for the same.
  29. BSTUseBetterApproach obj = new BSTUseBetterApproach();
  30. BinaryTreeNode root = obj.getTreeDetailsByLevelOrder();
  31.  
  32. // Call to isBST function with passing rootNode of the tree as argument.
  33. String result = isBST(root)?"BST":"Not BST";
  34.  
  35. System.out.println(result);
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement