LeetCode刷题笔录 Validate Binary Search Tree

来源:互联网 发布:白金数据日语 编辑:程序博客网 时间:2024/05/21 21:34

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.
上来先Brute force吧,没啥好说的。检查每个node的左子树的所有node都小于这个node,右子树的所有node都大于这个node。
public class Solution {    public boolean isValidBST(TreeNode root) {        if(root == null){            return true;        }        return isSubTreeLessThan(root.left, root.val) && isSubTreeGreaterThan(root.right, root.val) && isValidBST(root.left) && isValidBST(root.right);    }        public boolean isSubTreeLessThan(TreeNode node, int val){        if(node == null){            return true;        }        return node.val < val && isSubTreeLessThan(node.left, val) && isSubTreeLessThan(node.right, val);    }        public boolean isSubTreeGreaterThan(TreeNode node, int val){        if(node == null){            return true;        }        return node.val > val && isSubTreeGreaterThan(node.left, val) && isSubTreeGreaterThan(node.right, val);    }        }

改进一下。想到了AI课上学的alpha-beta pruning。一棵树的根为a,右子树为b,那么右子树的左儿子c的值一定是大于a且小于b。这样coding就好办了
public class Solution {    public boolean isValidBST(TreeNode root) {        return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);            }        public boolean isBST(TreeNode node, int alpha, int beta){        if(node == null){            return true;        }        if(alpha < node.val && node.val < beta){            return isBST(node.left, alpha, node.val) && isBST(node.right, node.val, beta);        }        else            return false;    }        }

还有一种方法:如果一棵树是BST,那么如果做一个in order traversal的话产生的数组应该是排好序的。这样就一边进行in order traversal,一边比较当前值是不是比前一个值大就行了。这里用了个static变量来记录之前的值,使其在递归时能被记住。如果用C++的话按引用传递就不需要static了。
public class Solution {    public static int previous = Integer.MIN_VALUE;    public boolean isValidBST(TreeNode root) {        if(root == null)            return true;        //the left sub tree        if(isValidBST(root.left) == false)            return false;        //the current node        if(root.val <= previous)            return false;        previous = root.val;                    //the right subtree        if(isValidBST(root.right) == false){            return false;        }                return true;    }}



0 0
原创粉丝点击