题目:

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. MySQL深入利用Ameoba实现读写分离

    3 ameoba安装配置   3.1 安装配置JDK [root@stu15 ~]# rpm -ivh jdk-7u67-linux-x64.rpm [root@stu15 ~]# cd /usr/j ...

  2. bea weblogic workshop中文乱码

    重装系统后,weblogic 8.1 workshop中的中文字体是乱码. 可通过菜单中的 Tools -> IDE Properties -> Display, 在Window font ...

  3. mysql实体关系(mysql学习五)

    实体关系  表设计 1:1 两个实体表内,存在相同的主键字段 如果记录的主键值等于另一个关系表内记录的主键值,则两条记录的对应为一一对应 优化上称为垂直分割 1:n 一个实体对应多个其他实体(一个班级 ...

  4. Js学习笔记一(鼠标事件.....)

    1.encodeURI与decodeURI()转化url为有效的url(能被识别) Url="http://news.baidu.com/p.php?id='测试'&姓名=hkui& ...

  5. 《安全参考》HACKCTO-201311-11

    小编的话 “晴空一鹤排云去,便引诗情到碧宵” 11月是一个让人思绪飞扬.感慨万千的时节. 就在这时,在我们小伙伴的并肩奋战下,第十一期<安全参考>又跟大家见面了. 你还在为女朋友在购物狂欢 ...

  6. php网页,想弹出对话框, 消息框 简单代码

    php网页,想弹出对话框, 消息框 简单代码 <?php echo "<script language=\"JavaScript\">alert(\&q ...

  7. DataTable使用总结

    1.DataTable数据去重 static void Main(string[] args) { DataTable dt = new DataTable();//创建表 DataColumn dc ...

  8. 第二节:AppDomain

    CLR COM服务器初始化时,会创建一个AppDomain.AppDomain是一组程序集的逻辑容器.CLR初始化时创建的第一个AppDomain称为默认的AppDomain,这个默认的AppDoma ...

  9. Python学习教程(learning Python)--2.2.2 Python全局和局部变量

    Python的变量也有全局和局部变量之分. 1. 局部变量 用在子函数里的变量称之为局部变量,其生命周期为该函数执行周期,即函数执行完后变量即不存在.由于局部变量和某个函数直接相关,故不同子函数里可以 ...

  10. laravel 笔记

    1.excel composer require maatwebsite/excel ~2.0.0 Maatwebsite\Excel\ExcelServiceProvider::class, 'Ex ...