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.
思路
- 用一个ResultStruct, 包含:
- isBST:表示以当前node为根节点的树是否为BST:
- minValue:表示以当前node为根节点的树,其最小的node值
- maxValue:表示以当前node为根节点的树,其最大的node值
- 从root开始遍历,每个节点均返回这个结构:
- root 为空时,其结构为
(true, Integer. MAX_VALUE, Integer.MIN_VALUE)
- 向下遍历其左右子节点,看其左右子节点返回的结构,是否有
isBST == false
,如果有,返回结构为(false,0,0)
- 如果其左child的
maxValue >= root.val
, 或者右child的minValue <= root.val
,说明当前节点不是BST,同样返回结构为(false,0,0)
- 如果以上都不满足,那么说明其是一个BST,返回结构为true,同时返回其最大和最小node的值
- root 为空时,其结构为
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class helpStruct {
private boolean isBST;
private int min;
private int max;
public helpStruct(boolean isBST, int min, int max) {
this.isBST = isBST;
this.min = min;
this.max = max;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
return helper(root).isBST;
}
private helpStruct helper(TreeNode root) {
if (root == null) {
return new helpStruct(true, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
helpStruct left = helper(root.left);
helpStruct right = helper(root.right);
if (!left.isBST || !right.isBST) {
return new helpStruct(false, 0, 0);
}
if ((root.left != null && left.max >= root.val) || (root.right != null && right.min <= root.val)) {
return new helpStruct(false, 0, 0);
}
return new helpStruct(true, Math.min(root.val, left.min), Math.max(root.val, right.max));
}
}