[Leetcode] 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?
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
/**
* 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 *> treeNode;
vector<int> nodeVal;
inoder(root,treeNode,nodeVal);
sort(nodeVal.begin(),nodeVal.end());
for(int i=;i<treeNode.size();++i)
treeNode[i]->val=nodeVal[i];
} void inoder(TreeNode *root,vector<TreeNode *> &treeNode,vector<int> &nodeVal)
{
if(root==NULL) return;
inoder(root->left,treeNode,nodeVal);
treeNode.push_back(root);
nodeVal.push_back(root->val);
inoder(root->right,treeNode,nodeVal);
}
};
方法二:
用三个指针,w1,w2分别指向第一、二个错误的地方。pre指向当前结点中序遍历中的前一个结点。因有两个结点交换了,所以二叉树的中序遍历中会出现违背有序的情况,一、即中序遍历中相邻的结点被交换,则违背有序的情况出现一次,如132456;二、中序遍历中不相邻的两个结点的值被交换,则出现两次违背有序情况,如153426.针对情况1,pre=3,w1=pre即为3,w2=root,即为2,在后续的遍历中没有违背有序的情况,所以交换w1和w2即可;针对情况2,找到第一个错误点后,w1 !=NULL了,所以,第二个错误点w2=root,第一逆序的前结点,第二逆序的后结点,交换两者即可。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *w1,*w2,*pre;
void recoverTree(TreeNode *root)
{
if(root==NULL) return;
w1=w2=pre=NULL;
find(root);
swap(w1->val,w2->val);
}
void find(TreeNode *root)
{
if(root==NULL) return;
find(root->left);
if(pre&&pre->val > root->val)
{
if(w1==NULL) //情况1
{
w1=pre;
w2=root;
}
else //情况2
w2=root;
}
pre=root;
find(root->right);
}
};
方法三
层次遍历中的Mirror方法,修改部分得到。真正的O(1)。
// Now O(1) space complexity
class Solution {
public:
void recoverTree(TreeNode *root) {
TreeNode *first = NULL, *second = NULL, *parent = NULL;
TreeNode *cur, *pre;
cur = root;
while (cur) {
if (!cur->left) {
if (parent && parent->val > cur->val) {
if (!first) first = parent;
second = cur;
}
parent = cur;
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
if (parent->val > cur->val) {
if (!first) first = parent;
second = cur;
}
parent = cur;
cur = cur->right;
}
}
}
if (first && second) swap(first->val, second->val);
}
};
[Leetcode] Recover binary search tree 恢复二叉搜索树的更多相关文章
- [leetcode]99. Recover Binary Search Tree恢复二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [LeetCode] Recover Binary Search Tree 复原二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [LeetCode] 99. Recover Binary Search Tree 复原二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [LeetCode] Validate Binary Search Tree 验证二叉搜索树
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...
- [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- 099 Recover Binary Search Tree 复原二叉搜索树
二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树. 详见:https://leetcode.com/problems/recover-binary-search-tree/submission ...
- [CareerCup] 4.5 Validate Binary Search Tree 验证二叉搜索树
4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原题,请参见我之前的博客Va ...
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
随机推荐
- less学习二---变量
less中声明的变量可以存储css属性值,还可以存储选择器,属性名,url以及@imporant等 变量声明及赋值格式:@variableName : varableValue ; //属性值 //l ...
- scala成长之路(1)基本语法和数据类型
scala作为JVM上的Lisp,是一种geek类型的编程语言,也一直是我等java程序员眼中的梦寐以求的一门技能,遂下定决心花一段时间好好学习scala.第一天学习,主要介绍与java在编程上的主要 ...
- Python学习手册之函数和模块
在上一篇文章中,我们介绍了 Python 的控制结构,现在我们介绍 Python 函数和模块. 查看上一篇文章请点击:https://www.cnblogs.com/dustman/p/9976234 ...
- ABAP CDS ON HANA-(7)CDSビューでの集約
Aggregate expression in CDS View An aggregate expression calculates a single value from an operand o ...
- python基础之反射、面向对象进阶
isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象,如果是返回True 1 class F ...
- VS2017发布微服务到docker
1.本文档以eShopOnContainers.sevices.identity为描述对象,并包含docker for windows的部分配置流程. 2.前置环境:win10操作系统.安装VS201 ...
- 【Keras案例学习】 sklearn包装器使用示范(mnist_sklearn_wrapper)
import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.l ...
- Java工程师笔试题整理[校招篇]
Java工程师笔试题整理[校招篇] 隔着两个月即将开始校招了.你是不是也想借着这个机会崭露头角,拿到某些大厂的offer,赢取白富美.走上人生巅峰?当然如果你还没能打下Java基础,一定要先打 ...
- MySQL用户权限控制一例
Preface I supposed we are encountering a situation that there's an anonymous user has connec ...
- jmeter无法启动的解决办法
jmeter下载地址: 链接: https://pan.baidu.com/s/15YhiPH-kNVxISEZ4Mxf_WA 提取码: 25sv jdk 8.0 下载地址: 链接: http ...