天天看点

【LeetCode】Validate Binary Search Tree 解题报告

今天CSDN博客发生异常,折腾了大半天终于发出了这篇博文。

【题目】

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.

【解析】

题意:判断一个二叉树是否为二分查找树。

何为二分查找树?1) 左子树的值都比根节点小;2) 右子树的值都比根节点大;3) 左右子树也必须满足上面两个条件。

需要注意的是,左子树的所有节点都要比根节点小,而非只是其左孩子比其小,右子树同样。这是很容易出错的一点是,很多人往往只考虑了每个根节点比其左孩子大比其右孩子小。如下面非二分查找树,如果只比较节点和其左右孩子的关系大小,它是满足的。

     5

  /     \

4      10

      /      \

    3        11

【错误代码示范】【NA】

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        if (root.left != null && root.val <= root.left.val) return false;
        if (root.right != null && root.val >= root.right.val) return false;
        return isValidBST(root.left) && isValidBST(root.right);
    }
}
           

【暴力遍历法】【AC】

从根节点开始递归,遍历所有的节点。并且在每个节点处,分别遍历其左右子树,判断其左子树的最大值比其小,右子树的最小值比其大。

时间复杂度为O(n^2)。

public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        if (!dfsLeft(root.left, root.val) || !dfsRight(root.right, root.val)) return false;
        return isValidBST(root.left) && isValidBST(root.right);
    }
    
    public boolean dfsLeft(TreeNode root, int value) {
        if (root == null) return true;
        if (root.val >= value) return false;
        return dfsLeft(root.left, value) && dfsLeft(root.right, value);
    }
    
    public boolean dfsRight(TreeNode root, int value) {
        if (root == null) return true;
        if (root.val <= value) return false;
        return dfsRight(root.left, value) && dfsRight(root.right, value);
    }
}
           

【失效O(n)解法:最大最小值法】【NA】

网上很用人用了Integer.MIN_VALUE和Integer.MAX_VALUE来辅助解决这道题,即遍历时记录一个当前允许的最大值和最小值。

public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        if (root.left == null && root.right == null) return true;
        return validate(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    
    public boolean validate(TreeNode root, int min, int max) {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return validate(root.left, min, root.val) && validate(root.right, root.val, max);
    }
}
           

但是现在的LeetCode已经更新了这道题,下面这种解法已经通不过了,因为LeetCode多了两个测试用例:

Input: {-2147483648,#,2147483647}
Output: false
Expected: true

【正确O(n)解法:中序遍历法】【AC】【推荐】

二分查找树的中序遍历结果是一个递增序列。

public class Solution {
    List<Integer> list = new ArrayList<Integer>();
    
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        if (root.left == null && root.right == null) return true;
        inOrderTraversal(root);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) <= list.get(i - 1)) return false;
        }
        return true;
     }
    
    public void inOrderTraversal(TreeNode root) {
        if (root == null) return;
        inOrderTraversal(root.left);
        list.add(root.val);
        inOrderTraversal(root.right);
    }
}
           

比较奇怪的是,这种方法和上面的暴力遍历方法在LeetCode上消耗的时间都是500ms。

【中序遍历法升级版】

看到网上一个比较高级的中序遍历写法,不需要额外的O(n)的空间,而且通过的时间为436ms。一起来学习一下。

public class Solution {
    // Keep the previous value in inorder traversal.
    TreeNode pre = null;
    
    public boolean isValidBST(TreeNode root) {
        // Traverse the tree in inorder.
        if (root != null) {
            // Inorder traversal: left first.
            if (!isValidBST(root.left)) return false;
            
            // Compare it with the previous value in inorder traversal.
            if (pre != null && root.val <= pre.val) return false;
            
            // Update the previous value.
            pre = root;
            
            // Inorder traversal: right last.
            return isValidBST(root.right);
        }
        return true;
     }
}
           

需要注意的是,TreeNode pre = null; 一定要在方法外边声明,原博客是写在方法里面的是不对的,因为写在里面的话,每次递归都是不同的pre。

参考来源:

http://huntfor.iteye.com/blog/2070278

http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

继续阅读