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).
分析:
解题思路可以根据bst的特性来,对于每个子树,我们给他们一个最小和最大的范围。
1 public class Solution { 2 public boolean isValidBST(TreeNode root) { 3 return vilidateChild(root, Long.MIN_VALUE, Long.MAX_VALUE); 4 } 5 6 public boolean vilidateChild(TreeNode node, long min, long max) { 7 if (node == null) return true; 8 if (node.val < max && node.val > min) { 9 return vilidateChild(node.left, min, node.val) && vilidateChild(node.right, node.val, max);10 } else {11 return false;12 }13 }14 }