题目:

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.

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
if (!root) return;
TreeNode *pre, *curr, *first=NULL, *second=NULL;
stack<TreeNode *> sta;
TreeNode *dummy = new TreeNode(INT_MIN);
dummy->left = root;
pre = dummy;
curr = root;
while ( !sta.empty() || curr )
{
if (curr){
sta.push(curr);
curr = curr->left;
}
else{
curr = sta.top();
sta.pop();
if ( !first ){
if ( pre->val > curr->val ){
first = pre;
second = curr;
}
}
else{
if ( curr->val < pre->val ){
second = curr;
break;
}
}
pre = curr;
curr = curr->right;
}
}
std::swap(first->val, second->val);
}
};

tips:

二叉查找树的中序遍历就是从小到大的输出(http://zh.wikipedia.org/wiki/二元搜尋樹)。

即从中序遍历的结果中找到两个需要交换的点。

为了简便,这里设定了虚根节点(初始化值为INT_MIN)保证不影响中序遍历的结果。具体的思想都参考的(http://www.cnblogs.com/TenosDoIt/p/3445682.html)。

通过这道题回顾了一下中序遍历的方法,并纠正了之前的中序遍历的一种自毁型的代码

http://www.cnblogs.com/xbf9xbf/p/4501655.html

在上面这道题中,写了一个自毁型的中序遍历代码(即中序遍历结束后,整个二叉树的所有节点都断了)。

在本道题中一开始沿用了这种自毁型的中序遍历代码,结果就可想而知了。通过这个点,给自己提个醒:以后再涉及到遍历这类的代码,尽量不要再写这种遍历一次就毁坏了数据结构的代码了。

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

第二次过这道题,直接学习的原来的代码。AC之后弄清楚了两个点:

(1)中序遍历是个模板,对BST的操作很多都依赖中序遍历。所以不管有没有first和second都要注意把中序遍历的代码写全了

(2)为什么找到第一个是first=pre而找到第二个是second=curr呢?曾就这个问题纠结过,后来猜测背后的思路可能是这样的:

   由于BST的两个节点位置错乱了,那么中序遍历必然有前面的节点要大于后面的。因此找到第一个不符合BST条件的,pre肯定是first;找到第二个不符合条件的curr肯定是second。

   另外还有一种特殊情况,就是被错位的两个点是挨着的,这样就更直接了。pre肯定是frist,curr肯定是second。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
stack<TreeNode*> sta;
TreeNode* first=NULL;
TreeNode* second=NULL;
TreeNode dummpy(INT_MIN);
dummpy.left = root;
TreeNode* pre = &dummpy;
TreeNode* curr = root;
while ( !sta.empty() || curr )
{
if ( curr )
{
sta.push(curr);
curr = curr->left;
}
else
{
curr = sta.top();
sta.pop();
if ( !first )
{
if (curr->val<pre->val)
{
first = pre;
second = curr;
}
}
else
{
if ( curr->val<pre->val)
{
second = curr;
break;
}
}
pre = curr;
curr = curr->right;
}
}
std::swap(first->val, second->val);
}
};

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

第三次过这道题,本来不想粘代码了,但前几次的代码实在太冗余了,于是贴一版新的。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
stack<TreeNode*> sta;
TreeNode *pre = new TreeNode(INT_MIN);
TreeNode *curr = root;
TreeNode *n1=NULL, *n2=NULL;
while ( !sta.empty() || curr )
{
if ( curr )
{
sta.push(curr);
curr = curr->left;
}
else
{
curr = sta.top(); sta.pop();
if ( pre->val > curr->val )
{
if ( !n1 )
{
n1 = pre;
n2 = curr;
}
else
{
n2 = curr;
break;
}
}
pre = curr;
curr = curr->right;
}
}
if (n1) swap(n1->val, n2->val);
}
};

【Recover Binary Search Tree】cpp的更多相关文章

  1. 【遍历二叉树】07恢复二叉搜索树【Recover Binary Search Tree】

    开一个指针数组,中序遍历这个二叉搜索树,将节点的指针依次保存在数组里, 然后寻找两处逆序的位置, 中序便利里BST得到的是升序序列 ++++++++++++++++++++++++++++++++++ ...

  2. 【Validate Binary Search Tree】cpp

    题目: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is define ...

  3. 【Lowest Common Ancestor of a Binary Search Tree】cpp

    题目: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in th ...

  4. 【二叉查找树】03验证是否为二叉查找树【Validate Binary Search Tree】

    本质上是递归遍历左右后在与根节点做判断,本质上是后序遍历 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ...

  5. 【Unique Binary Search Trees】cpp

    题目: Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For e ...

  6. 【Convert Sorted List to Binary Search Tree】cpp

    题目: Given a singly linked list where elements are sorted in ascending order, convert it to a height ...

  7. 【Convert Sorted Array to Binary Search Tree】cpp

    题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BST ...

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

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

  9. 【leetcode】Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

随机推荐

  1. void指针(void*)用法

    首先看一段测试代码: #include <stdio.h> int void_test(void* data) { ; num = *(int*)data; printf("nu ...

  2. IOS屏幕布局

    1.iPad和iPhone的屏幕布局 在IB中,屏幕或控件的尺寸以点为单位.在视网膜技术中,1个点包括4个像素,而没有采用视网膜屏幕技术的还是1个点包括1个像素. 2.绝对布局和相对布局 3.使用Au ...

  3. C# 测试程序运行时间和cpu使用时间

    方法一 Stopwatch类测试程序运行时间和cpu使用时间 添加命名空间using System.Diagnostics;使用实例如下 private Stopwatch sw = new Stop ...

  4. linux服务器之LVS、Nginx和HAProxy负载均衡器对比

    linux服务器之LVS.Nginx和HAProxy负载均衡器对比. LVS特点:  1.抗负载能力强,使用IP负载均衡技术,只做分发,所以LVS本身并没有多少流量产生:  2.稳定性.可靠性好,自身 ...

  5. Hive深入浅出

    1.  Hive是什么 1) Hive是什么? 这里引用 Hive wiki 上的介绍: Hive is a data warehouse infrastructure built on top of ...

  6. QTP获取系统时间并自定义格式

    function GetDateTime(Nowstr)          Dim Currentdatetime           Dim YY   'Year          Dim MM   ...

  7. 6.24AppCan移动开发者大会价值30万的展示机会归了谁?

    最近,小编的邮箱都被挤爆了! 来自开发者的邮件一封封涌进邮箱,VIP展位申请,TOP30 APP评选,感谢大家的积极参与,展位有限,APP名额有限,开发者的热情无限. 经过谨慎筛选.综合评定后,以下5 ...

  8. 【6.24-北京】AppCan移动开发者大会:最新议程曝光

    6.24,首届AppCan移动开发者大会将在北京国际会议中心召开. 大会以“平台之上,应用无限”为主题,旨在探讨在“互联网+双创”的大潮下,通过移动互联网技术.思维.模式,帮助开发者/创业者实现创新创 ...

  9. hdu 5101 Select

    题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5101 Select Description One day, Dudu, the most cleve ...

  10. hdu 1509 Windows Message Queue

    题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=1509 Windows Message Queue Description Message queue ...