力扣 题目99- 验证二叉搜索树
2022/7/27 23:23:15
本文主要是介绍力扣 题目99- 验证二叉搜索树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
题目
题解
在力扣 题目98- 验证二叉搜索树中 我们知道了 中序遍历后的二叉搜索树 应该为递增 那么出错就应该是有部分递减 那么我们在98题的基础上 反向检测 保存减少数列的开头与结尾进行交换
代码
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 //即减少序列的第一个数与最后一个数交换 17 class Solution { 18 public: 19 void recoverTree(TreeNode* root) { 20 TreeNode* last = new TreeNode(INT_MAX); 21 TreeNode* max = new TreeNode(INT_MAX); 22 TreeNode* min = new TreeNode(INT_MAX); 23 stack<TreeNode*> ergodic; 24 while (root != nullptr || !ergodic.empty()) { 25 if (root != nullptr) { 26 ergodic.push(root); 27 root = root->left; 28 } 29 else 30 { 31 if (ergodic.top()->val < last->val) { 32 if (max->val == INT_MAX) { 33 max = last; 34 } 35 min = ergodic.top(); 36 } 37 last = ergodic.top(); 38 root = ergodic.top()->right; 39 ergodic.pop(); 40 } 41 } 42 swap(max->val, min->val); 43 } 44 45 vector<int> inorderTraversal(TreeNode* root) { 46 vector<int> result; 47 stack<TreeNode*> ergodic; 48 while (root != nullptr || !ergodic.empty()) { 49 if (root != nullptr) { 50 ergodic.push(root); 51 root = root->left; 52 } 53 else 54 { 55 result.push_back(ergodic.top()->val); 56 root = ergodic.top()->right; 57 ergodic.pop(); 58 } 59 } 60 return result; 61 } 62 63 }; 64 65 int main() { 66 Solution sol; 67 TreeNode* head2 = new TreeNode(2); 68 TreeNode* head3 = new TreeNode(3, nullptr, head2); 69 TreeNode* head1 = new TreeNode(1, head3, nullptr); 70 sol.recoverTree(head1); 71 vector<int> resultforeach = sol.inorderTraversal(head1); 72 for (int i = 0; i < resultforeach.size(); i++) { 73 cout << resultforeach[i] << " "; 74 } 75 76 }View Code
这篇关于力扣 题目99- 验证二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?
- 2024-05-09企业src漏洞挖掘-有意思的命令执行
- 2024-05-08阿里云域名注册流程,分享给第一次购买域名的新手站长!