【leetcode】Recover Binary Search Tree
Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
中序遍历解法O(n)space
1 /** 2 * Definition for binary tree 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 void recoverTree(TreeNode *root) { 13 vector<TreeNode *> nodes; 14 dfs(root,nodes); 15 int index1=-1; 16 int index2=-1; 17 for(int i=1;i<nodes.size();i++) 18 { 19 if(nodes[i]->val<nodes[i-1]->val) 20 { 21 if(index1==-1) index1=i-1; 22 index2=i; 23 } 24 } 25 26 int tmp=nodes[index1]->val; 27 nodes[index1]->val=nodes[index2]->val; 28 nodes[index2]->val=tmp; 29 return; 30 31 } 32 33 void dfs(TreeNode *root,vector<TreeNode *> &nodes) 34 { 35 if(root==NULL) return; 36 dfs(root->left,nodes); 37 nodes.push_back(root); 38 dfs(root->right,nodes); 39 } 40 };
直接在中序遍历中进行判断,需要记录遍历中的前一个元素
如果前一个元素比当前元素大,则说明存在错误
1 /** 2 * Definition for binary tree 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 void recoverTree(TreeNode *root) { 13 14 TreeNode *firstError=NULL; 15 TreeNode *secondError=NULL; 16 TreeNode *pre=NULL; 17 18 19 dfs(root,pre,firstError,secondError); 20 21 int tmp=firstError->val; 22 firstError->val=secondError->val; 23 secondError->val=tmp; 24 } 25 26 void dfs(TreeNode *root,TreeNode *&pre,TreeNode *&firstError,TreeNode *&secondError) 27 { 28 if(root==NULL) return; 29 30 dfs(root->left,pre,firstError,secondError); 31 32 if(pre!=NULL&&pre->val>root->val) 33 { 34 if(firstError==NULL) firstError=pre; 35 secondError=root; 36 } 37 pre=root; 38 39 dfs(root->right,pre,firstError,secondError); 40 } 41 };
分类:
算法研究
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~