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. C#进程间通讯技术-整理。

    原文:C#进程间通讯技术-整理. 扩展阅读:http://www.cnblogs.com/joye-shen/archive/2012/06/16/2551864.html 一.进程间通讯的方式 1) ...

  2. Katana 还是Owin ? 本地自承载

    使用Owin 将Web项目脱离 IIS确实很特别..... 由此 ,可以衍生出,一个新的通信渠道,本地Server的自承载. 1 Node.js 2 Python 3 Ruby 4 Owin (C#- ...

  3. CMAKE 生成VS2008静态库工程 与 CMAKE使用,CMakeLists.txt编写总结

    cmake -G"Visual Studio 9 2008 Win64" 以上命令得用cd命令切换到顶层CMakeLists.txt的当前目录,才能生效 以下是CMakeLists ...

  4. SOSP 文档 - Windows Azure 存储:具有强一致性的高可用性云存储服务

    之前,我们在第 23 届 ACM操作系统原理研讨会 (SOSP)上发布了一篇文章,其中介绍了 Windows Azure存储的内部详细信息. 您可以在此处找到该文章.此次大会还发布了一段视频讲话( ...

  5. Oracle优化笔记

    2016-11-22   子查询:标量子查询 内联视图(in-line view) 半连接/反连接   标量子查询 select 后跟子查询 类似自定义函数 可用开窗函数之类的改写   内联视图(in ...

  6. poj 2836 Rectangular Covering(状态压缩dp)

    Description n points are given on the Cartesian plane. Now you have to use some rectangles whose sid ...

  7. WebService-调用第三方提供的webService服务

    互联网上面有很多的免费webService服务,我们可以调用这些免费的WebService服务,将一些其他网站的内容信息集成到我们的Web应用中显示,下面就以获取天气预报数据和查询国内手机号码归属地为 ...

  8. Eclipse+Java+OpenCV246人脸识别

    1.环境搭建:见上一篇博客 整个项目的结构图: 2.编写DetectFaceDemo.java,代码如下: package com.njupt.zhb.test; import org.opencv. ...

  9. [Angular 2] WebStorm - Managing Imports

    Some tips for import libaray by using webstorm: // Alt + Enter --> Auto Import // Ctrl + Alt + o ...

  10. Android ActionBar完全解析,使用官方推荐的最佳导航栏(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/18234477 本篇文章主要内容来自于Android Doc,我翻译之后又做了些加工 ...