[LintCode/LeetCode] Validate Binary Search Tree

发布时间:2019-06-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LintCode/LeetCode] Validate Binary Search Tree脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

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

Note

第一种,先跑左子树的DFS:如果不满足,返回false.
左子树分支判断完成后,pre = root.left(因为唯一给pre赋值的语句是pre = root,所以运行完dfs(root.left)之后,pre = root.left)。
然后,若pre.val,也就是root.left.val,大于等于root.val的话,不满足BST定义,也返回false
否则,继续执行pre = root,(现在去判断root.right,所以用root.valroot.right.val比较。)不满足就返回false.
如果跑完了右子树的DFS,还没有返回false,返回true.
第二种DFS,用root的值给左右子树的递归设定边界。

Solution

DFS I

public class Solution {
    TreeNode pre = null;
    public boolean isValidBST(TreeNode root) {
        return dfs(root);   
    }
    public boolean dfs(TreeNode root) {
        if (root == null) return true;
        if (!dfs(root.left)) return false;
        if (pre != null && pre.val >= root.val) return false;
        pre = root;
        if (!dfs(root.right)) return false;
        return true;
    }

}

DFS II

class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValid(root, null, null);
    }
    private boolean isValid(TreeNode node, Integer min, Integer max) {
        if (node == null) return true;
        if (min != null && node.val <= min) return false;
        if (max != null && node.val >= max) return false;
        return isValid(node.left, min, node.val) && isValid(node.right, node.val, max);
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LintCode/LeetCode] Validate Binary Search Tree全部内容,希望文章能够帮你解决[LintCode/LeetCode] Validate Binary Search Tree所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: