LeetCode OJ - Validate Binary Search Tree
来源:互联网 发布:刷广告软件 编辑:程序博客网 时间:2024/06/05 19:53
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.
分析:结果取决于左子树与右子树的情况。故可以写出 check(root) = check(root->left) && check(root->right),由此写出递归代码为:
bool check(root) { if(!root) return true; return check(root->left) && check(root->right);}
在递归中加入边界参数(部分题目也可以维护两个集合)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isValidBST(TreeNode *root) { return check(root, INT_MIN, INT_MAX); } bool check(TreeNode *root, int min, int max) { if(!root) return true; if(min < root->val && root->val < max) { return check(root->left, min, root->val) && check(root->right, root->val, max); } return false; }};
也可以写成下面的代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isValidBST(TreeNode *root) { return check(root, INT_MIN, INT_MAX); } bool check(TreeNode *root, int min, int max) { if(!root) return true; return min < root->val && check(root->left, min, root->val) && \ root->val < max && check(root->right, root->val, max); }};
这样充分体现出了root与root->left和root->right之间的关系为逻辑与运算,代码跟清晰。
如果没有想清楚使用范围,题目解决会非常杂乱,使用范围界定上面的代码非常漂亮。
0 0
- LeetCode OJ:Validate Binary Search Tree
- LeetCode OJ - Validate Binary Search Tree
- LeetCode OJ - Validate Binary Search Tree
- LeetCode OJ Validate Binary Search Tree
- leetcode oj java 98. Validate Binary Search Tree
- Leetcode OJ 98 Validate Binary Search Tree [Medium]
- 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
- Intent 回调数据步骤
- 如何做一个葫芦在Xbox 360上的VPN工作
- 第九章 后向传播算法(分类)
- stop-all.sh 命令无法停止hadoop集群
- 定制scrollView来处理自动显示与隐藏键盘
- LeetCode OJ - Validate Binary Search Tree
- 黑马程序员 - 学习笔记5 流程控制语句
- 将博客搬至cnblogs
- Struts2.x+Spring3.x+Hibernate4.x 整合(七)整合struts RESTful
- hdu 1426 Sudoku Killer(DFS)
- Android开发环境搭建笔记
- PHPCMS URL规则(频道页(栏目页列表页)二级域名,内容页主域名)
- mysql存储过程详解
- POJ1797——Heavy Transportation