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.
二刷還是看答案做出來(lái)的辜妓,這道題有幾個(gè)坑:
- root的val可能超出Integer的范圍萝挤,比如有一個(gè)test case給的root.val = 2147483647
- 要注意BST的定義里蚜印,每個(gè)節(jié)點(diǎn)左邊的子數(shù)val必須小于該節(jié)點(diǎn)刽宪,右邊的子樹(shù)必須大于該節(jié)點(diǎn)唯鸭。不只是直接的left, right, 而是左邊所有的、右邊所有的藏斩,這個(gè)概念可能會(huì)有模糊理解
/**
* 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做: