@@ -36,16 +36,27 @@ Explanation: The root node's value is 5 but its right child's value is 4.
3636```
3737
3838## 思路
39+ ### 中序遍历
3940这道题是让你验证一棵树是否为二叉查找树(BST)。 由于中序遍历的性质` 如果一个树遍历的结果是有序数组,那么他也是一个二叉查找树(BST) ` ,
4041我们只需要中序遍历,然后两两判断是否有逆序的元素对即可,如果有,则不是BST,否则即为一个BST。
42+
43+ ### 定义法
44+ 根据定义,一个结点若是在根的左子树上,那它应该小于根结点的值而大于左子树最大值;若是在根的右子树上,那它应该大于根结点的值而小于右子树最小值。也就是说,每一个结点必须落在某个取值范围:
45+ 1 . 根结点的取值范围为(考虑某个结点为最大或最小整数的情况):(long_min, long_max)
46+ 2 . 左子树的取值范围为:(current_min, root.value)
47+ 3 . 右子树的取值范围为:(root.value, current_max)
48+
4149## 关键点解析
4250
4351- 二叉树的基本操作(遍历)
4452- 中序遍历一个二叉查找树(BST)的结果是一个有序数组
4553- 如果一个树遍历的结果是有序数组,那么他也是一个二叉查找树(BST)
4654
4755## 代码
56+ ### 中序遍历
57+ * 语言支持:JS
4858
59+ JavaScript Code:
4960``` js
5061/*
5162 * @lc app=leetcode id=98 lang=javascript
@@ -94,7 +105,67 @@ var isValidBST = function(root) {
94105};
95106
96107```
108+ ### 定义法
109+ * 语言支持:C++
97110
111+ C++ Code:
112+ ``` C++
113+ /* *
114+ * Definition for a binary tree node.
115+ * struct TreeNode {
116+ * int val;
117+ * TreeNode *left;
118+ * TreeNode *right;
119+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
120+ * };
121+ */
122+ // 递归
123+ class Solution {
124+ public:
125+ bool isValidBST(TreeNode* root) {
126+ return helper(root, LONG_MIN, LONG_MAX);
127+ }
128+ private:
129+ bool helper(const TreeNode* root, long min, long max) {
130+ if (root == nullptr) return true;
131+ if (root->val >= max || root->val <= min) return false;
132+ return helper(root->left, min, root->val) && helper(root->right, root->val, max);
133+ }
134+ };
135+
136+ // 循环
137+ class Solution {
138+ public:
139+ bool isValidBST(TreeNode* root) {
140+ if (root == nullptr) return true;
141+ auto ranges = queue<pair<long, long>>();
142+ ranges.push(make_pair(LONG_MIN, LONG_MAX));
143+ auto nodes = queue<const TreeNode* >();
144+ nodes.push(root);
145+ while (!nodes.empty()) {
146+ auto sz = nodes.size();
147+ for (auto i = 0; i < sz; ++i) {
148+ auto range = ranges.front();
149+ ranges.pop();
150+ auto n = nodes.front();
151+ nodes.pop();
152+ if (n->val >= range.second || n->val <= range.first) {
153+ return false;
154+ }
155+ if (n->left != nullptr) {
156+ ranges.push(make_pair(range.first, n->val));
157+ nodes.push(n->left);
158+ }
159+ if (n->right != nullptr) {
160+ ranges.push(make_pair(n->val, range.second));
161+ nodes.push(n->right);
162+ }
163+ }
164+ }
165+ return true;
166+ }
167+ };
168+ ```
98169## 相关题目
99170
100171[230.kth-smallest-element-in-a-bst](./230.kth-smallest-element-in-a-bst.md)
0 commit comments