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
分析:此题需要注意的是一个平衡二叉树的条件为左子树的val中最大的值需要小于root.val,右子树的val最小值需要大于root.val,一旦有任意子树不满足上述条件,则该树不是平衡二叉树。
class ResultType {
boolean isValid;
int max;
int min;
ResultType(boolean a, int b, int c) {
isValid = a;
max = b;
min = c;
}
}
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
public boolean isValidBST(TreeNode root) {
ResultType rt = helper(root);
return rt.isValid;
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(true, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if (!left.isValid || !right.isValid) {
return new ResultType(false, 0, 0);
}
if ((root.left != null && left.max >= root.val) || (root.right != null && right.min <= root.val)) {
return new ResultType(false, 0, 0);
}
return new ResultType(true,
Math.max(root.val, right.max),
Math.min(root.val, left.min));
}
}