Medium
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.
Example 1:
2
/ \
1 3
Binary tree [2,1,3]
, return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3]
, return false.
二刷还是看答案做出来的,这道题有几个坑:
- root的val可能超出Integer的范围,比如有一个test case给的root.val = 2147483647
- 要注意BST的定义里,每个节点左边的子数val必须小于该节点,右边的子树必须大于该节点。不只是直接的left, right, 而是左边所有的、右边所有的,这个概念可能会有模糊理解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null){
return true;
}
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long low, long high){
if (root.val <= low || root.val >= high){
return false;
}
if (root.left != null && !helper(root.left, low, root.val)){
return false;
}
if (root.right != null && !helper(root.right, root.val, high)){
return false;
}
return true;
}
}
这道题还可以用inorder traversal做: