[LeetCode] Validate Binary Search Tree 解题报告
来源:互联网 发布:网络2017流行歌曲 编辑:程序博客网 时间:2024/06/05 21:00
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.
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.» Solve this problem
[解题思路]
对于每一个子树,限制它的最大,最小值,如果超过则返回false。
对于根节点,最大最小都不限制;
每一层节点,左子树限制最大值小于根,右子树最小值大于根;
但是比较有趣的是,在递归的过程中还得不断带入祖父节点的值。
或者,中序遍历该树,然后扫描一遍看是否递增。
[Code]
递归
红字部分是关键点。不把变量遗传下去的话,没法解决如下例子:
{10,5,15,#,#,6,20}
1: bool isValidBST(TreeNode *root) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: return VerifyBST(root, false, false, 0,0);
5: }
6: bool VerifyBST(TreeNode* root, bool left, bool right, int lmax, int rmin)
7: {
8: if(root== NULL)
9: return true;
10: if(left && root->val >= lmax) return false;
11: if(right && root->val <=rmin) return false;
12: bool leftValid = VerifyBST(root->left, true,right
, root->val, rmin);
13: bool rightValid = VerifyBST(root->right,left
, true, lmax, root->val);
14: return leftValid&&rightValid;
15: }
Updates:
换个看起来简洁的
1: bool isValidBST(TreeNode *root) {
2: return IsValidBST(root, INT_MIN, INT_MAX);
3: }
4: bool IsValidBST(TreeNode* node, int MIN, int MAX)
5: {
6: if(node == NULL)
7: return true;
8: if(node->val > MIN
9: && node->val < MAX
10: && IsValidBST(node->left,MIN,node->val)
11: && IsValidBST(node->right,node->val,MAX))
12: return true;
13: else
14: return false;
15: }
0 0
- [LeetCode]Validate Binary Search Tree, 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- [LeetCode] Validate Binary Search Tree 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- LeetCode(98) Validate Binary Search Tree解题报告
- [leetcode] 98. Validate Binary Search Tree 解题报告
- [Leetcode] 98. Validate Binary Search Tree 解题报告
- [leetcode]98. Validate Binary Search Tree@Java解题报告
- [LeetCode]Binary Search Tree Iterator,解题报告
- 【LeetCode】Recover Binary Search Tree 解题报告
- LeetCode-Binary Search Tree Iterator-解题报告
- [LeetCode] Recover Binary Search Tree 解题报告
- Leetcode 98. 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
- python生成随机数组
- [LeetCode] Valid Parentheses 解题报告
- MSSQL Server数据的完整性
- MVP模式在android的使用
- [LeetCode] Valid Sudoku 解题报告
- [LeetCode] Validate Binary Search Tree 解题报告
- [LeetCode] Wildcard Matching, Solution
- [LeetCode] Word Search 解题报告
- [LeetCode] ZigZag Conversion 解题报告
- [LeetCode] Add Binary 解题报告
- [LeetCode] Anagrams 解题报告
- 关于 mysql中非null判断
- [LeetCode] Best Time to Buy and Sell Stock Solution
- [LeetCode] Best Time to Buy and Sell Stock II Solution