Skip to content

Commit fd87cf2

Browse files
committed
added 86. Validate Binary Search Tree
1 parent 886cb51 commit fd87cf2

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
这道题其实应该算是 Easy 难度的吧。
2+
3+
不过可以顺便复习一下 BST 的基本概念:
4+
5+
1. 左边所有子节点的值都要小于当前节点
6+
2. 右边所有自节点的值都要大于当前节点
7+
3. 左子树与右子树仍为 BST
8+
9+
背概念最没意思了,要知道 BST 的本质是对**二分搜索**思想在数据结构上的一种体现。
10+
所以保持有序是基本条件,二叉树如何有序?左边永远小于右边。就是这么简单粗暴。
11+
12+
对于第三条,傻子应该都能听出其递归性的特征。
13+
14+
所以要验证是否为 BST,优先考虑递归解法。(另外一句话,十个二叉树,九个递归解。)
15+
16+
但这道题容易疏忽之处在于:由于其递归性,下一层的节点不仅要与当前节点比较,还应与当前节点的上层节点比较。
17+
18+
具体举例如下:
19+
20+
4
21+
/^\
22+
1 7
23+
/ \
24+
3 9
25+
^
26+
27+
该树便不是 BST,因为第三层的节点值(3)小于根节点值(4)。从本质上讲,便是不符合有序的条件。
28+
29+
所以我们可以 suppose 每一个节点都应该有一个边界,即 min 与 max.
30+
但稍稍验证,便可知,并非所有节点都有边界,如 1 与 9 便分别没有左边界与右边界。
31+
32+
有人会说,怎么没有,左边界是 INT_MIN,右边界是 INT_MAX。
33+
这样的判断非常武断,不过可以提交试试,就知道 test case 有多么恶心了,哈哈。
34+
35+
所以我们的递归函数,必备的除了 min 与 max 外,应该增加两个 `bool` 值,记录是否存在左边界与右边界。
36+
37+
代码三行,不多说了。
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#include "solution.h"
2+
#include <iostream>
3+
4+
int main()
5+
{
6+
Solution s;
7+
TreeNode root(4);
8+
TreeNode node1(1);
9+
TreeNode node2(7);
10+
TreeNode node3(5);
11+
TreeNode node4(9);
12+
13+
root.left = &node1;
14+
root.right = &node2;
15+
node2.left = &node3;
16+
node2.right = &node4;
17+
18+
std::cout << s.isValidBST(&root) << std::endl;
19+
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <cstddef>
2+
3+
struct TreeNode {
4+
int val;
5+
TreeNode *left;
6+
TreeNode *right;
7+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
};
9+
10+
class Solution {
11+
public:
12+
bool isValidBST(TreeNode *root) {
13+
return isValidBST(root, false, false, 0, 0);
14+
}
15+
bool isValidBST(TreeNode *root, bool left, bool right, int min, int max)
16+
{
17+
if (!root) return true;
18+
else if ((left && root->val <= min) || (right && root->val >= max)) return false;
19+
else return isValidBST(root->left, left, true, min, root->val) && isValidBST(root->right, true, right, root->val, max);
20+
}
21+
};

0 commit comments

Comments
 (0)