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. LeetCode_Partition List

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr ...

  2. BZOJ2697: 特技飞行

    2697: 特技飞行 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 607  Solved: 363[Submit][Status] Descript ...

  3. [WPF] 将普通的Library工程,改造成WPF Custom Control 的Library

    1. 添加References PresentationCore PresentationFramework System.Xaml WindowsBase2. 修改AssemblyInfo.xsus ...

  4. hdu 5313 Bipartite Graph(dfs染色 或者 并查集)

    Problem Description Soda has a bipartite graph with n vertices and m undirected edges. Now he wants ...

  5. genymotion+Oracle VM VirtualBox + eclipse + appium 脚本运行慢解决步骤

    genymotion+Oracle VM VirtualBox + eclipse + appium 脚本运行慢解决步骤 1.lenove 机器启动时按F1 进入bios 设置,设置cpu virtu ...

  6. MySQL server version for the right syntax to use near 'type=InnoDB' at line 1

    转载请注明出处:http://blog.csdn.net/bettarwang/article/details/40180271 在执行一个Hibernate的演示样例时,配置了<propert ...

  7. VMware vSphere 5.5的12个更新亮点(3)

    端口镜像 有时有必要捕捉网络中的数据包来追踪问题.最新版本的vSphere包括一个增强版的开源数据包分析器tcpdump和一些镜像端口的选项以捕捉各种场所的流量.您可以捕获虚拟网卡,虚拟交换机,以及主 ...

  8. [RxJS] Updating Data with Scan

    You often need to update the data flowing through the stream with custom logic based on what you nee ...

  9. Hadoop集群运行JNI程序

    要在Hadoop集群运行上运行JNI程序,首先要在单机上调试程序直到可以正确运行JNI程序,之后移植到Hadoop集群就是水到渠成的事情. Hadoop运行程序的方式是通过jar包,所以我们需要将所有 ...

  10. Chapter 4: Spring and AOP:Spring's AOP Framework -- draft

    Spring's AOP Framework Let's begin by looking at Spring's own AOP framework - a proxy-based framewor ...