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
 
 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
vector<TreeNode *> nodes;
dfs(root,nodes);
int index1=-;
int index2=-;
for(int i=;i<nodes.size();i++)
{
if(nodes[i]->val<nodes[i-]->val)
{
if(index1==-) index1=i-;
index2=i;
}
} int tmp=nodes[index1]->val;
nodes[index1]->val=nodes[index2]->val;
nodes[index2]->val=tmp;
return; } void dfs(TreeNode *root,vector<TreeNode *> &nodes)
{
if(root==NULL) return;
dfs(root->left,nodes);
nodes.push_back(root);
dfs(root->right,nodes);
}
};
 
 
直接在中序遍历中进行判断,需要记录遍历中的前一个元素
如果前一个元素比当前元素大,则说明存在错误

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) { TreeNode *firstError=NULL;
TreeNode *secondError=NULL;
TreeNode *pre=NULL; dfs(root,pre,firstError,secondError); int tmp=firstError->val;
firstError->val=secondError->val;
secondError->val=tmp;
} void dfs(TreeNode *root,TreeNode *&pre,TreeNode *&firstError,TreeNode *&secondError)
{
if(root==NULL) return; dfs(root->left,pre,firstError,secondError); if(pre!=NULL&&pre->val>root->val)
{
if(firstError==NULL) firstError=pre;
secondError=root;
}
pre=root; dfs(root->right,pre,firstError,secondError);
}
};

最新文章

  1. s:form标签
  2. cf 731f
  3. 给VIM安装插件。让ubuntu的vim强大起来
  4. 《JavaScript模式》第3章 字面量和构造函数
  5. 初识 Android
  6. 黄聪:利用Aspose.Word控件实现Word文档的操作(转)
  7. c#自动更新+安装程序的制作 (转)
  8. 利用Inltellj创建javadoc ,用jd2chm创建chm
  9. ThinkPHP 笔记
  10. .Net中String和StringBuilder的区别
  11. 在一般处理文件中访问Session需要添加IRequiresSessionState
  12. hdu 1520 Anniversary party(入门树形DP)
  13. 前端之JavaScript--基础
  14. Linux 下编译安装xCache命令速记
  15. 关于datagrid中数据条件颜色问题
  16. JS高程关于ajax的学习笔记
  17. 根据javabean转换为mysql建表语句与mapper内容
  18. Verification of Model Transformations A Survey of the State-of-the-Art 模型转换的验证 对现状的调查
  19. thymeleaf 标签的使用
  20. NPM安装步骤

热门文章

  1. Spring的Bean之Bean的基本概念
  2. Yii2 advanced版API接口开发 基于RESTful架构的 配置、实现、测试
  3. Orchard源码分析(5):Host相关(Orchard.Environment.DefaultOrchardHost类)
  4. LINUX命令总结 -------来自 水滴娃娃 的CSDN
  5. 来聊聊apply和call
  6. JavaScript数组属性与方法
  7. 电脑开机黑屏,显示Reboot and Select proper boot device!
  8. Swift编程语言资料合集
  9. hdu.5211.Mutiple(数学推导 &amp;&amp; 在logn的时间内求一个数的所有因子)
  10. java系列-使用maven创建web项目(二)