Validate Binary Search Tree

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).

思路
  1. 分支算法:如果是BST,那么他的左、右子树都应该是BST。
  2. 用一个helper class,存储当前树是否为BST,其minValue, maxValue.
  3. 递归停止条件,当current Node是null时,那么返回BST为true,minValue = Integer.MAX_VALUE, maxValue = Integer.MIN_VALUE
  4. 对当前节点分别求其Left, Right Child的结果,返回这个helper class
  5. 如果Left, Right的结果任一不是BST,那么当前以当前这个节点为根的树就不是BST,返回这个helper class(false)
  6. 如果Left, Right都是BST,还需要检查当前节点为根的树是否为BST,检查的方式看Left返回的最大值是否比root小,同时,如果Right返回的最小值,是否比root大。如果任一不满足,则代表这个tree不是BST,返回helper class(false)
  7. 如果以上都满足,则需要返回当前节点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));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容