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,那么他的左、右子樹都應該是BST。
- 用一個helper class,存儲當前樹是否為BST,其minValue, maxValue.
- 遞歸停止條件,當current Node是null時,那么返回BST為true,minValue = Integer.MAX_VALUE, maxValue = Integer.MIN_VALUE
- 對當前節點分別求其Left, Right Child的結果,返回這個helper class
- 如果Left, Right的結果任一不是BST,那么當前以當前這個節點為根的樹就不是BST,返回這個helper class(false)
- 如果Left, Right都是BST,還需要檢查當前節點為根的樹是否為BST,檢查的方式看Left返回的最大值是否比root小,同時,如果Right返回的最小值,是否比root大。如果任一不滿足,則代表這個tree不是BST,返回helper class(false)
- 如果以上都滿足,則需要返回當前節點tree的helper class(true, 更新minValue, maxValue)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class ResultType {
public boolean isBST;
public int minValue;
public int maxValue;
public ResultType(boolean isBST, int minValue, int maxValue) {
this.isBST = isBST;
this.minValue = minValue;
this.maxValue = maxValue;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
boolean result = helper(root).isBST;
return result;
}
private ResultType helper(TreeNode root) {
//遞歸停止條件
if (root == null) {
return new ResultType(true, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
ResultType leftResult = helper(root.left);
ResultType rightResult = helper(root.right);
//判斷左右子樹是否都有BST,任一不是,則當前不是
if (!leftResult.isBST || !rightResult.isBST) {
return new ResultType(false, 0, 0);
}
// 如果左右子樹是BST,但左右子樹與當前節點組成的數不是BST,結果仍然不是BST
if (root.left != null && leftResult.maxValue >= root.val
|| root.right != null && rightResult.minValue <= root.val) {
return new ResultType(false, 0 ,0);
}
//如果以上都通過,則說明當前節點的樹是BST,返回resultType(跟新當前節點的樹的最大、最小值)
return new ResultType(true,
Math.min(root.val, leftResult.minValue),
Math.max(root.val, rightResult.maxValue));
}
}