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的更多相关文章

  1. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  2. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  3. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  4. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. java中如果需要精确的计算答案,请避免使用double类型与float类型

    double类型与float类型主要用于科学计算与工程计算而设计的,用于二进制浮点计算.对于普通计算通常是结果不准确的,所以对于普通的浮点数的加减法等,解决的方法需要用int,long,BigDeci ...

  2. linux下串口的阻塞和非阻塞操作

    有两个可以进行控制串口阻塞性(同时控制read和write):一个是在打开串口的时候,open函数是否带O_NDELAY:第二个是可以在打开串口之后通过fcntl()函数进行控制. 阻塞的定义: 对于 ...

  3. ZOJ3519-Beautiful People:最长上升子序列的变形

    Beautiful People Special JudgeTime Limit: 10000/5000MS (Java/Others)Memory Limit: 128000/64000KB (Ja ...

  4. XMPP通讯开发-服务器好友获取以及监听状态变化

    在 XMPP通讯开发-好友获取界面设计   我们设计了放QQ的列表功能,这里我们获取我们服务器上的 数据. 这一部分知识我们可以查看smack_3_3_0/smack_3_3_0/documentat ...

  5. Android程序Crash时的异常上报

    转载请注明来源:http://blog.csdn.net/singwhatiwanna/article/details/17289479 前言 大家都知道,android应用不可避免的会发生crash ...

  6. Jquery与DOM对象

    在第一次学习jquery中,常常会不能分辨DOM对象和Jquery对象,下面我们就简诉一下它们之间的关系和区别 1.DOM对象(Document Object Model) 文档对象模型,每一份DOM ...

  7. PL/SQL破解方法(不需要注册码)

    打开注册表在run下输入regedit删除1.HKEY_CURRENT_USER/Software/Allround Automations2.HKEY_CURRENT_USER/Software/M ...

  8. 《第一行代码》学习笔记14-UI(3)

    1. (1)所有控件都是直接或间接继承自View,所用的所有布局都是直接或间接继承自ViewGroup的. (2)View是Android中一种最基本的UI组件,可以在屏幕上绘制一块矩形区域,并能响应 ...

  9. WIN7中组件服务中的DCOM配置找不到Microsoft Excel应用程序的解决办法

    转自:http://blog.csdn.net/lploveme/article/details/8215265 在运行栏中输入命令:dcomcnfg,打开组件服务管理窗口,但是却发现找不到Micro ...

  10. hdu5355 Cake(构造)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud Cake Time Limit: 2000/1000 MS (Java/Other ...