力扣 题目98- 验证二叉搜索树

题目

题解

中序遍历是左中右 那么根据 二叉搜索树的性质我们可以发现 左<中<右 那么对应就是中序遍历就是递增的

那么我们可以在力扣 题目94- 二叉树的中序遍历 直接加入判断

while (root != nullptr || !ergodic.empty()) {
            if (root != nullptr) {
                ergodic.push(root);
                root = root->left;
            }
            else
            {
                if (result.empty() || ergodic.top()->val > result.back()) {
                    result.push_back(ergodic.top()->val);
                    root = ergodic.top()->right;
                    ergodic.pop();
                }
                else
                {
                    return 0;
                }
            }
        }
return 1;

可以通过

那么既然是递增 我们只需要比较前面一个数 那么就能减少空间 所以改变一下 first是记录是否是第一次 因为此时last不存在 必然通过 

while (root != nullptr || !ergodic.empty()) {
            if (root != nullptr) {
                ergodic.push(root);
                root = root->left;
            }
            else
            {
                if (first || ergodic.top()->val > last) {
                    last = ergodic.top()->val;
                    root = ergodic.top()->right;
                    ergodic.pop();
                    first = 0;
                }
                else
                {
                    return 0;
                }
            }
        }
        return 1;

代码

 1 #include<iostream>
 2 #include<vector>
 3 #include<stack>
 4 using namespace std;
 5 
 6 
 7 struct TreeNode {
 8     int val;
 9     TreeNode* left;
10     TreeNode* right;
11     TreeNode() : val(0), left(nullptr), right(nullptr) {}
12     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
13     TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
14 };
15 //遍历
16 class Solution {
17 public:
18     bool isValidBST(TreeNode* root) {
19         int last = INT_MIN;
20         bool first = 1;
21         stack<TreeNode*> ergodic;
22         while (root != nullptr || !ergodic.empty()) {
23             if (root != nullptr) {
24                 ergodic.push(root);
25                 root = root->left;
26             }
27             else
28             {
29                 if (first || ergodic.top()->val > last) {
30                     last = ergodic.top()->val;
31                     root = ergodic.top()->right;
32                     ergodic.pop();
33                     first = 0;
34                 }
35                 else
36                 {
37                     return 0;
38                 }
39             }
40         }
41         return 1;
42     }
43 
44 };
45 
46 int main() {
47     Solution sol;
48     TreeNode* head3 = new TreeNode(3);
49     TreeNode* head7 = new TreeNode(7);
50     TreeNode* head4 = new TreeNode(4);
51     TreeNode* head6 = new TreeNode(6, head3, head7);
52     TreeNode* head5 = new TreeNode(5, head4, head6);
53     bool result1 = sol.isValidBST(head5);
54     cout << result1 << endl;
55 
56 }
View Code

 

posted @ 2022-07-24 17:16  无聊的阿库娅  阅读(28)  评论(0编辑  收藏  举报