Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

验证二叉搜索树 #80

Open
louzhedong opened this issue Nov 8, 2018 · 0 comments
Open

验证二叉搜索树 #80

louzhedong opened this issue Nov 8, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第98题

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

思路

树一般都可以采用递归的方式来解决,但本题需要注意的是每个节点需要和它的父节点以及父节点的父节点做比较

解答

function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function (root) {
  var helper = function (root, min, max) {
    if (root == null) return true;
    if (min != null && root.val <= min) return false
    if (max != null && root.val >= max) return false;
    return helper(root.left, min, root.val) && helper(root.right, root.val, max);
  }
  
  return helper(root, null, null);
};



var right = new TreeNode(15);
right.left = new TreeNode(6);
right.right = new TreeNode(20);
var root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = right;

console.log(isValidBST(root));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant