[LeetCode/LinkedIn] Valid Binary Search Tree

来源:互联网 发布:芒果店长软件下载 编辑:程序博客网 时间:2024/06/16 19:11

Solution 1. In order Traversal

public boolean isValidBST(TreeNode root) {    ArrayList<TreeNode> list = new ArrayList<TreeNode>();    inOrderBST(root,list);    boolean start = true;    int prev = 0;    for(TreeNode node : list){        int i = node.val;        if(start){            prev = i;            start = false;        }else {            if(i<=prev){                return false;            }            prev = i;        }    }    return true;}public void inOrderBST(TreeNode root, ArrayList list) {    if (root == null) {        return;    }    inOrderBST(root.left,list);    list.add(root);    inOrderBST(root.right,list);}

Solution 2. Advance In-order traversal

//global variable to keep the previous visited nodeprivate Node prev = null;public boolean isValidBST(Node root) { if (root == null) {   return true; } if (!isValidBST(root.left)) {   return false; } if (prev != null && root.val <= prev.val) {   return false; } prev = root; return isValidBST(root.right);}

Solution 3:

//min & max value check approach//each iteration, current root being the min/maxpublic boolean isValidBST(Node root) { if (root == null) {   return false; } //This will not work if the initial value is these two return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);}private boolean isValidBST(Node root, int min, int max) { if (root == null) {   return true; } if (root.val > min && root.val < max) {   return isValidBST(root.left, min, root.val)          && isValidBST(root.right,root.val , max); } return false;}
0 0
原创粉丝点击