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.
Solution and Precautions:
The basic idea is to in-order traverse the whole tree and find the reversed pair and fix them. The following are based on the same in-order traverse but using different space.
(1) using average O(N) space. use perform regular in-order traverse on the whole tree and store all the node pointers in an allocated vector or array, find the reversed pair in the array, and swap the values pointed by the stored pointers. The allocated array cost O(N) space averagely
(2) average O(log N) space but O(N) in worst case. Still do in-order traverse but without the the allocated array in (1), this could be down by keeping two pointers prev and current which point to the consecutive nodes in the in-order sequence, during one pass in-order traverse, we keep comparing them (pre->val, current->val) and we can get the first and second pointers to the swapped wrong nodes. After finishing the in-order traverse, you swap back the two wrong nodes. And we are down. Since we do recursive in-order traverse, we still allocate additional memory in the stack which is O(hight of the tree), so the space we use is actually average O(log N) space but O(N) in worst case.
(3) real constant space. In order to get constant space, we have to be able to do the in-order traverse without using the stack, then we might need to get the help of the “threaded binary tree”. By following the threaded binary tree, we make use of the NULL node of the leaf node by making the right NULL child of the leaf node point to the next node in the in-order sequence, we are able to do the in-order traverse without using stack and thus constant memory, combing (2) we only need another two pointers Prev, Curret, to keep traversing the while tree in in-order and another two Ptr1, Ptr2 to keep record of the reversed nodes. Then then finish swapping them. And all these are be achieved by using constant number of pointers. This is constant space solution.
/**
* 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 inOrder(TreeNode *root){
if(root->left ) inOrder(root->left);
if(pre == NULL) pre = root;
else if(pre-> val > root->val ){
if(first == NULL)
first = pre;
second = root;
}
pre = root;
if(root->right ) inOrder(root->right);
}
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return;
first = NULL;
second = NULL;
pre = NULL ;
inOrder(root);
int temp = first->val ;
first->val = second->val;
second->val = temp;
}
private :
TreeNode * first;
TreeNode * second;
TreeNode * pre;
};
reference :http://tech-wonderland.net/blog/leetcode-recover-binary-search-tree.html#comment-2742
LeetCode_Recover Binary Search Tree的更多相关文章
- [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode: Convert sorted list to binary search tree (No. 109)
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- [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] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
随机推荐
- Codeforces 540D Bad Luck Island
http://codeforces.com/problemset/problem/540/D 题目大意: 会出石头.剪刀.布的人分别有r,s,p个,他们相互碰到的概率相同,输的人死掉,问最终活下去的人 ...
- MVC每层的职责
MVC模式把应用程序分割成三层:模型.视图和控制器. 模型:模型代表着核心的业务逻辑和数据.模型封装了域实体的属性和行为,并暴露出了实体的属性. 视图: 视图负责转换模型并把它传递给表示层.视图应关注 ...
- emacs vim IDE
原本想花点时间来学习下Vim或者emacs,结果在网上搜索到这篇文章 骂战挺多的,但是也长见识 http://bbs.csdn.net/topics/390306165 下面是windows下的ema ...
- zoj2314 经典 无源汇有上下界最大流 并输出可行流
ZOJ Problem Set - 2314 Reactor Cooling Time Limit: 5 Seconds Memory Limit: 32768 KB Specia ...
- xm学习笔记
1关于静态网页的制作 html主要负责页面的结构+css页面的美观+js与用户的交互. 2html 有标签体的标签: <p></p> <span></spa ...
- WPF - 如何引用external dll中图片
前几天一直想引用别的DLL里面的一个图片.总是出现各种各样问题,一气之下将图片拷贝到当前Project中,运行良好.虽然知道引用图片,就1.2.列出来的2点就够了. 1. The Build Acti ...
- JVM运行时内存结构
原文转载自:http://my.oschina.net/sunchp/blog/369707 1.JVM内存模型 JVM运行时内存=共享内存区+线程内存区 1).共享内存区 共享内存区=持久带+堆 持 ...
- C++ Primer 学习笔记_84_模板与泛型编程 --模板特化
模板与泛型编程 --模板特化 引言: 我们并不总是能够写出对全部可能被实例化的类型都最合适的模板.某些情况下,通用模板定义对于某个类型可能是全然错误的,通用模板定义或许不能编译或者做错误的事情;另外一 ...
- Homebrew新一代OS X套件管理工具 高速安装Git
在Mac上安装一些开源程序,除了自己下下载.编译( ./configure && make && make install) 之外,通常最方便的选择就是用套件管理工具來 ...
- Button和ImageButton
Button----button ImageButton----图片button 共同拥有特征: 都能够作为一个button产生点击事件 不同点 1. Button有text的属性.ImageButt ...