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.
- A single node tree is a BST
Example
An example:
2
/
1 4
/
3 5
The above binary tree is serialized as {2,1,4,#,#,3,5}
(in level order).
分治法,优化思路是只要记录并返回每棵树的最大值最小值即可。和左子树的max,右子树的min比,只要left.max < root.val < right.min就合格了。
resultType包括min, max, isValid。
注意一个点就是null节点的处理。如果返回Integer.MAX_VALUE和Integer.MIN_VALUE,之后真正想要比较大小的时候为了避免最大值输入不出错,一定要判断一下你左子树的最大值来源到底是因null来的还是真实的最大值。(见注释)
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: The root of binary tree. * @return: True if the binary tree is BST, or false */ private class ResultType { int min; int max; boolean isValid; public ResultType(int min, int max, boolean isValid) { this.min = min; this.max = max; this.isValid = isValid; } } public boolean isValidBST(TreeNode root) { // write your code here return helper(root).isValid; } private ResultType helper(TreeNode root) { if (root == null) { return new ResultType(Integer.MAX_VALUE, Integer.MIN_VALUE, true); } ResultType left = helper(root.left); ResultType right = helper(root.right); int minValue = Math.min(root.val, Math.min(left.min, right.min)); int maxValue = Math.max(root.val, Math.max(left.max, right.max)); if (!left.isValid || !right.isValid) { return new ResultType(0, 0, false); } // 重要!! // 这里一定要加判断root.left, root.right是不是null, // 以确定我数值比较的来源是正确的而不是因null传过来的数字 if (root.left != null && left.max >= root.val || root.right != null && right.min <= root.val) { return new ResultType(0, 0, false); } return new ResultType(minValue, maxValue, true); } }