[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
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode | Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- 元旦快乐
- 大数据能在色情行业里做什么
- 2013记录整理
- Eclipse 开发WEB项目 webcontent下lib中的jar包不自动加载的问题
- Happy New Year
- [LeetCode] Validate Binary Search Tree
- Median of Two Sorted Arrays (JAVA)
- 2014记录
- Android游戏开发十日通(8)- Box2D的例子和学习小结
- Nunit 2.5.5的使用总结
- WMI--Windows API--IWbemLocator
- 浅析动态内存分配及Malloc/free的实现
- Android之二维码的生成与解析
- 无监督学习算法