Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- public class CheckForBST {
- // function to find out the inorder traversal of the tree.
- private static void inOrder(BinaryTreeNode root, ArrayList<Integer> list){
- if(root == null)
- return;
- inOrder(root.left, list);
- list.add(root.data);
- inOrder(root.right, list);
- }
- // function to find out the inorder traversal of the tree.
- private static boolean isBST(BinaryTreeNode root){
- ArrayList<Integer> list = new ArrayList<>();
- inOrder(root, list);
- // In java you can check if the arrayList is sorted or not in foll way.
- ArrayList<Integer> sortedList = (ArrayList<Integer>) list.clone();
- Collections.sort(sortedList);
- return list.equals(sortedList);
- }
- public static void main(String[] args) {
- // 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.
- BSTUseBetterApproach obj = new BSTUseBetterApproach();
- BinaryTreeNode root = obj.getTreeDetailsByLevelOrder();
- // Call to isBST function with passing rootNode of the tree as argument.
- String result = isBST(root)?"BST":"Not BST";
- System.out.println(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement