【leetcode】Recover Binary Search Tree
2024-10-18 23:27:14
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);
}
};
最新文章
- s:form标签
- cf 731f
- 给VIM安装插件。让ubuntu的vim强大起来
- 《JavaScript模式》第3章 字面量和构造函数
- 初识 Android
- 黄聪:利用Aspose.Word控件实现Word文档的操作(转)
- c#自动更新+安装程序的制作 (转)
- 利用Inltellj创建javadoc ,用jd2chm创建chm
- ThinkPHP 笔记
- .Net中String和StringBuilder的区别
- 在一般处理文件中访问Session需要添加IRequiresSessionState
- hdu 1520 Anniversary party(入门树形DP)
- 前端之JavaScript--基础
- Linux 下编译安装xCache命令速记
- 关于datagrid中数据条件颜色问题
- JS高程关于ajax的学习笔记
- 根据javabean转换为mysql建表语句与mapper内容
- Verification of Model Transformations A Survey of the State-of-the-Art 模型转换的验证 对现状的调查
- thymeleaf 标签的使用
- NPM安装步骤
热门文章
- Spring的Bean之Bean的基本概念
- Yii2 advanced版API接口开发 基于RESTful架构的 配置、实现、测试
- Orchard源码分析(5):Host相关(Orchard.Environment.DefaultOrchardHost类)
- LINUX命令总结 -------来自 水滴娃娃 的CSDN
- 来聊聊apply和call
- JavaScript数组属性与方法
- 电脑开机黑屏,显示Reboot and Select proper boot device!
- Swift编程语言资料合集
- hdu.5211.Mutiple(数学推导 &;&; 在logn的时间内求一个数的所有因子)
- java系列-使用maven创建web项目(二)