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.

Hide Tags Tree Depth-first Search

SOLUTION 1:

采用递归+全局变量完成:

空间复杂度是O(logn)

REF: http://huntfor.iteye.com/blog/2077665
这一篇讲得蛮清楚:
http://yucoding.blogspot.com/2013/03/leetcode-question-75-recover-binary.html

具体的思路,还是通过中序遍历,只不过,不需要存储每个节点,只需要存一个前驱即可。

例如1,4,3,2,5,6

1.当我们读到4的时候,发现是正序的,不做处理

2.但是遇到3时,发现逆序,将4存为第一个错误节点,3存为第二个错误节点

3.继续往后,发现3,2又是逆序了,那么将第2个错误节点更新为2

如果是这样的序列:1,4,3,5,6同上,得到逆序的两个节点为4和3。

========================================

这里我们补充一下,为什么要替换第二个节点而不是第一个节点:
e.g. The correct BST is below:


The inorder traversal is :  1 3 4 6 7 8 10 13
14

Find the place which the order is wrong.
       
Wrong order: 1 3 8 6 7 4 10 13
14

FIND:          
     
   8 6
       
Then we
find:     
   
   7 4
       
8, 6 是错误的序列, 但是,7,4也是错误的序列。
       
因为8,6前面的序列是正确的,所以8,6一定是后面的序列交换来的。
       
而后面的是比较大的数字,也就是说8一定是被交换过来的。而7,4
       
中也应该是小的数字4是前面交换过来的。

用反证法来证明:
       
假设:6是后面交换过来的
       
推论: 那么8比6还大,那么8应该也是后面交换来的,
       
这样起码有3个错误的数字了
       
而题目是2个错误的数字,得证,只应该是8是交换过来的。
结论就是:我们需要交换的是:8, 4.

 public class RecoverTree {
TreeNode pre = null;
TreeNode first = null;
TreeNode second = null; public void recoverTree(TreeNode root) {
inOrder(root); // swap the value of first and second node.
int tmp = first.val;
first.val = second.val;
second.val = tmp;
} public void inOrder(TreeNode root) {
if (root == null) {
return;
} // inorder traverse.
inOrder(root.left); /*
Find the place which the order is wrong.
For example: 1 3 4 6 7 8 10 13 14
Wrong order: 1 3 8 6 7 4 10 13 14
FIND: ___
Then we find: ___
8, 6 是错误的序列, 但是,7,4也是错误的序列。
因为8,6前面的序列是正确的,所以8,6一定是后面的序列交换来的。
而后面的是比较大的数字,也就是说8一定是被交换过来的。而7,4
中也应该是小的数字4是前面交换过来的。 用反证法来证明:
假设:6是后面交换过来的
推论: 那么8比6还大,那么8应该也是后面交换来的,
这样起码有3个错误的数字了
而题目是2个错误的数字,得证,只应该是8是交换过来的。
*/ // 判断 pre 是否已经设置
if (pre != null && pre.val > root.val) {
if (first == null) {
// 首次找到反序.
first = pre;
second = root;
} else {
// 第二次找到反序,更新Second.
second = root;
}
} pre = root; // inorder traverse.
inOrder(root.right);
}

SOLUTION 2:

也可以采用非递归方法,不需要加全局变量,空间复杂度是O(logn):

 public void recoverTree1(TreeNode root) {
if (root == null) {
return;
} TreeNode node1 = null;
TreeNode node2 = null; TreeNode pre = null; Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode cur = root; while (true) {
while (cur != null) {
s.push(cur);
cur = cur.left;
} if (s.isEmpty()) {
break;
} TreeNode node = s.pop(); if (pre != null) {
// invalid order
if (pre.val > node.val) {
if (node1 == null) {
node1 = pre;
node2 = node;
} else {
node2 = node;
}
}
} pre = node; cur = node.right;
} int tmp = node1.val;
node1.val = node2.val;
node2.val = tmp; return;
}

SOLUTION 3:

还有更厉害的作法,可以达到O(1)的空间复杂度。以后再补上。

ref: http://fisherlei.blogspot.com/2012/12/leetcode-recover-binary-search-tree.html

=================

代码请参考主页君的实现:
请戳主页君的代码哦

LeetCode: Recover Binary Search Tree 解题报告的更多相关文章

  1. 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)

    [LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...

  2. LeetCode: Validate Binary Search Tree 解题报告

    Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST) ...

  3. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  4. 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...

  5. 【LeetCode】669. Trim a Binary Search Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  6. 【LeetCode】98. Validate Binary Search Tree 解题报告(Python & C++ & Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 BST的中序遍历是有序的 日期 题目地址:ht ...

  7. 【LeetCode】501. Find Mode in Binary Search Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  8. 【LeetCode】701. Insert into a Binary Search Tree 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. 【LeetCode】700. Search in a Binary Search Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

随机推荐

  1. python获取公网ip,本地ip及所在国家城市等相关信息收藏

    python获取公网ip的几种方式       from urllib2 import urlopen   my_ip = urlopen('http://ip.42.pl/raw').read() ...

  2. IBM NOTES

    归档含义 邮件容量超过指定的邮件服务器的容量时,会受到警告信息.选择 Archive-Settings 可以设置邮件备份的规则,把邮箱里的部分邮件转移到本地的另一个指定文件夹(如 图 4).当您需要做 ...

  3. 自己开发能在asp.net项目正常使用的定时器WebTimer,让定时器听话起来

    简述: iis是一个很不错的服务器,有很多很好用的特性来支持网站运行,但有时候这些特性却会影响到我们开发者的一些操作.比如我们需要定时运行做一些操作,但由于iis的利用应用程序池来管理这种方式会让网站 ...

  4. Windows 下安装 swoole 具体步骤(php)

    Windows 下安装 swoole 具体步骤: Swoole,原本不支持在Windows下安装的,所以我们要安装Cygwin来使用.在安装Cygwin下遇到了很多坑,百度经验上的文档不是很全,所以我 ...

  5. POJ.3145.Common Substrings(后缀数组 倍增 单调栈)

    题目链接 \(Description\) 求两个字符串长度不小于k的公共子串对数. \(Solution\) 求出ht[]后先减去k,这样对于两个后缀A',B',它们之间的贡献为min{ht(A)}( ...

  6. HDU.1536.S-Nim(博弈论 Nim)

    题目链接 \(Description\) 给定一个集合S,每次只能拿S中某个元素个数的石子.每组数据有多组询问,询问给出m堆石子个数,问先手是否必胜.有多组数据. 1. 首先对操作数组排个序,再预处理 ...

  7. COGS.1317.数列操作c(分块 区间加 区间求和)

    题目链接 #include<cmath> #include<cstdio> #include<cctype> #include<algorithm> u ...

  8. 潭州课堂25班:Ph201805201 爬虫基础 第三课 urllib (课堂笔记)

    Python网络请求urllib和urllib3详解   urllib是Python中请求url连接的官方标准库,在Python2中主要为urllib和urllib2,在Python3中整合成了url ...

  9. 潭州课堂25班:Ph201805201 并发(进程,线程)二 第十二课 (课堂笔记

    线程与进程的其他相关操作 import threading # 线程 import multiprocessing # 进程 import socket import time def wo(): g ...

  10. 2017-2018-20172309 『Java程序设计』课程 结对编程练习_四则运算_第三周

    2017-2018-20172309 『Java程序设计』课程 结对编程练习_四则运算 组队成员: 仇夏 学号: 20172310 博客地址: @王志伟 四则运算第一周博客 @仇夏四则运算第一周博客 ...