[LeetCode] Validate Binary Search Tree

来源:互联网 发布:网络作家稿费 编辑:程序博客网 时间:2024/05/22 04:54

问题:

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.
分析:

一道简单的递归题。但很容易脑子一热,写出下面这样的代码:

class Solution {public:bool isValidBST(TreeNode *root) {if (!root) return true;if (root->left && root->left->val >= root->val) return false;if (root->right && root->right->val <= root->val) return false;return (isValidBST(root->left) && isValidBST(root->right));}};

这个代码的错误的地方在于,它没有判断一个node的左subtree中是不是所有的node都小于自己;右边也是类似。它仅仅判断了它左右两个children是不是小于自己。这是不够的。正确的代码如下:


class Solution {public:bool isValidBSTHelper(TreeNode *root, int min_val, int max_val) {if (!root)return true;if (root->val >= max_val || root->val <= min_val)return false;return (isValidBSTHelper(root->left, min_val, root->val) && isValidBSTHelper(root->right, root->val, max_val));}bool isValidBST(TreeNode *root) {int max_val = INT_MAX;int min_val = INT_MIN;return isValidBSTHelper(root, min_val, max_val);}};


0 0
原创粉丝点击