【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/

时间: 2024-08-26 03:02:33

【LeetCode】Validate Binary Search Tree 解题报告的相关文章

LeetCode: Validate Binary Search Tree 解题报告

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 co

LeetCode: Recover Binary Search Tree 解题报告

Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? c

[leetcode]Validate Binary Search Tree @ Python

原题地址:https://oj.leetcode.com/problems/validate-binary-search-tree/ 题意:检测一颗二叉树是否是二叉查找树. 解题思路:看到二叉树我们首先想到需要进行递归来解决问题.这道题递归的比较巧妙.让我们来看下面一棵树: 4 /    \ 2 6 /    \   /   \  1      3 5    7 对于这棵树而言,怎样进行递归呢?root.left这棵树的所有节点值都小于root,root.right这棵树的所有节点值都大于roo

LeetCode :: Validate Binary Search Tree[详细分析]

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 b

LeetCode: Validate Binary Search Tree [098]

[题目] 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

LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告

https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between t

【LeetCode】Recover Binary Search Tree 解题报告

[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? [解析] 题意:二叉搜索树中,有两个结点的位置

LeetCode: Convert Sorted Array to Binary Search Tree 解题报告

Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending order, convert it to a height balanced BST.SOLUTION 1:使用递归解决. base case: 当索引值超过时,返回null. 递归主体:构造根节点,调用递归构造左右子树.并将左右子树挂在根节点上. 返回值:返回构造的根节点. GITHUB: https:

LeetCode 700 Search in a Binary Search Tree 解题报告

题目要求 Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 题目分析及