Answer by checking for inorder traversal for list in ascending order


  • 0
    A

    I applied a simple logic and it worked. I just wrote a function that returns a inorder traversal of the binary search tree. This list should have values in ascending order and if not then it is not a binary search tree. Below is the code.

    public class Solution {
            public boolean isValidBST(TreeNode root) {
                boolean flag = true;
                if(root== null) return true;
                List<Integer> list = new ArrayList<Integer>();
                retrieve(root,list);
                for(int i =1; i<list.size(); i++){
                    if(!(list.get(i) > list.get(i-1)))
                        return false;
                }
                return true;
            }
            // get a list with inorder traversal of the binary search tree
            public void retrieve(TreeNode node,List<Integer> list){
                if(node == null) return ;
                retrieve(node.left,list);
                list.add(node.val);
                retrieve(node.right,list);
        }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.