开一个指针数组,中序遍历这个二叉搜索树,将节点的指针依次保存在数组里,

然后寻找两处逆序的位置,

中序便利里BST得到的是升序序列

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

二叉搜索树(BST)中的两个节点不小心被交换了下。

不改变其结构的情况下恢复这个树。

笔记:

用O(n)的空间复杂度的方法很直接。你能否设计一个常量空间的解决法方案?

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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?

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
 
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 * int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
vector<TreeNode *> inorderTraversal(TreeNode *root)
{
    stack<TreeNode *> s;
    vector<TreeNode *> path;
    TreeNode *p = root;
    while(p != NULL || !s.empty())
    {
        while(p != NULL)
        {
            s.push(p);
            p = p->left;
        }
        if(!s.empty())
        {
            p = s.top();
            path.push_back(p);
            s.pop();
            p = p->right;
        }
    }
    return path;
}

void recoverTree(TreeNode *root)
{
    vector<TreeNode *> inTrav = inorderTraversal(root);
    TreeNode *left, *right;
    int tmp;
    for (int i = 0; i < inTrav.size() - 1; ++i)
    {
        if (inTrav[i]->val > inTrav[i + 1]->val)
        {
            left = inTrav[i];
            break;
        }
    }
    for (int i = inTrav.size() - 1; i > 0; --i)
    {
        if (inTrav[i]->val < inTrav[i - 1]->val)
        {
            right = inTrav[i];
            break;
        }
    }
    tmp = left->val;
    left->val = right->val;
    right->val = tmp;
    return ;
}

// 树中结点含有分叉,
//                  6
//              /       \
//             7         2
//           /   \
//          1     4
//               / \
//              3   5
int main()
{
    TreeNode *pNodeA1 = CreateBinaryTreeNode(6);
    TreeNode *pNodeA2 = CreateBinaryTreeNode(7);
    TreeNode *pNodeA3 = CreateBinaryTreeNode(2);
    TreeNode *pNodeA4 = CreateBinaryTreeNode(1);
    TreeNode *pNodeA5 = CreateBinaryTreeNode(4);
    TreeNode *pNodeA6 = CreateBinaryTreeNode(3);
    TreeNode *pNodeA7 = CreateBinaryTreeNode(5);

ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
    ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
    ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);

PrintTree(pNodeA1);

cout << "before recover" << endl;
    vector<TreeNode *> ans = inorderTraversal(pNodeA1);

for (int i = 0; i < ans.size(); ++i)
    {
        cout << ans[i]->val << " ";
    }
    cout << endl;

recoverTree(pNodeA1);

cout << "after recover" << endl;
    ans.clear();
    ans = inorderTraversal(pNodeA1);

for (int i = 0; i < ans.size(); ++i)
    {
        cout << ans[i]->val << " ";
    }
    cout << endl;

DestroyTree(pNodeA1);
    return 0;
}

输出结果:
before recover
1 7 3 4 5 6 2
after recover
1 2 3 4 5 6 7
BinaryTree.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
#ifndef _BINARY_TREE_H_
#define _BINARY_TREE_H_

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode *CreateBinaryTreeNode(int value);
void ConnectTreeNodes(TreeNode *pParent,
                      TreeNode *pLeft, TreeNode *pRight);
void PrintTreeNode(TreeNode *pNode);
void PrintTree(TreeNode *pRoot);
void DestroyTree(TreeNode *pRoot);

#endif /*_BINARY_TREE_H_*/

BinaryTree.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
 
#include <iostream>
#include <cstdio>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//创建结点
TreeNode *CreateBinaryTreeNode(int value)
{
    TreeNode *pNode = new TreeNode(value);

return pNode;
}

//连接结点
void ConnectTreeNodes(TreeNode *pParent, TreeNode *pLeft, TreeNode *pRight)
{
    if(pParent != NULL)
    {
        pParent->left = pLeft;
        pParent->right = pRight;
    }
}

//打印节点内容以及左右子结点内容
void PrintTreeNode(TreeNode *pNode)
{
    if(pNode != NULL)
    {
        printf("value of this node is: %d\n", pNode->val);

if(pNode->left != NULL)
            printf("value of its left child is: %d.\n", pNode->left->val);
        else
            printf("left child is null.\n");

if(pNode->right != NULL)
            printf("value of its right child is: %d.\n", pNode->right->val);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

printf("\n");
}

//前序遍历递归方法打印结点内容
void PrintTree(TreeNode *pRoot)
{
    PrintTreeNode(pRoot);

if(pRoot != NULL)
    {
        if(pRoot->left != NULL)
            PrintTree(pRoot->left);

if(pRoot->right != NULL)
            PrintTree(pRoot->right);
    }
}

void DestroyTree(TreeNode *pRoot)
{
    if(pRoot != NULL)
    {
        TreeNode *pLeft = pRoot->left;
        TreeNode *pRight = pRoot->right;

delete pRoot;
        pRoot = NULL;

DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}




 
 
 
 
 
 
 
 

【遍历二叉树】07恢复二叉搜索树【Recover Binary Search Tree】的更多相关文章

  1. [Swift]LeetCode99. 恢复二叉搜索树 | Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  2. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  3. 二叉搜索树BST(Binary Search Tree)

    二叉搜索树(Binary Search Tree)也叫二叉排序树或二叉查找树.它满足以下性质: 1.非空左子树的所有键值小于其根结点的键值: 2.非空右子树的所有键值大于其根结点的键值: 3.左右子树 ...

  4. 二叉搜索树(Binary Search Tree)--C语言描述(转)

    图解二叉搜索树概念 二叉树呢,其实就是链表的一个二维形式,而二叉搜索树,就是一种特殊的二叉树,这种二叉树有个特点:对任意节点而言,左孩子(当然了,存在的话)的值总是小于本身,而右孩子(存在的话)的值总 ...

  5. 数据结构-二叉搜索树(BST binary search tree)

    本文由@呆代待殆原创,转载请注明出处:http://www.cnblogs.com/coffeeSS/ 二叉搜索树简介 顾名思义,二叉搜索树是以一棵二叉树来组织的,这样的一棵树可以用一个链表数据结构来 ...

  6. 原生JS实现二叉搜索树(Binary Search Tree)

    1.简述 二叉搜索树树(Binary Search Tree),它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值: 若它的右子树不空,则右子 ...

  7. 【数据结构05】红-黑树基础----二叉搜索树(Binary Search Tree)

    目录 1.二分法引言 2.二叉搜索树定义 3.二叉搜索树的CRUD 4.二叉搜索树的两种极端情况 5.二叉搜索树总结 前言 在[算法04]树与二叉树中,已经介绍过了关于树的一些基本概念以及二叉树的前中 ...

  8. 二叉搜索树(Binary Search Tree)

    二叉搜索树(BST,Binary Search Tree),也称二叉排序树或二叉查找树. 二叉搜索树:一棵二叉树,可以为空:如果不为空,满足以下性质: 非空左子树的所有键值小于其根结点的键值: 非空右 ...

  9. [Swift]LeetCode98. 验证二叉搜索树 | Validate Binary Search Tree

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  10. [Swift]LeetCode173. 二叉搜索树迭代器 | Binary Search Tree Iterator

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. JAVA读文件和写文件的的代码模版

    有的时候经常为真么读写文件最合理发愁,因为JAVA提过读写文件的方式太多了(C更甚至,fopen & open又有多少人傻傻分不去,更别说ReadFile了). 这里个人绝对比较好的写法,仅供 ...

  2. Spring Cloud 微服务五:Spring cloud gateway限流

    前言:在互联网应用中,特别是电商,高并发的场景非常多,比如:秒杀.抢购.双11等,在开始时间点会使流量爆发式地涌入,如果对网络流量不加控制很有可能造成后台实例资源耗尽.限流是指通过指定的策略削减流量, ...

  3. 在express项目中使用redis

    在express项目中使用redis 准备工作 安装redis 安装redis桌面管理工具:Redis Desktop Manager 项目中安装redis:npm install redis 开始使 ...

  4. WebApi 中使用 Session

    1. 在 Global.asax.cs 文件中加入session支持 protected void Application_Start() { AreaRegistration.RegisterAll ...

  5. zoj 3716 Ribbon Gymnastics【神奇的计算几何】

    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3716 来源:http://acm.hust.edu.cn/vjudg ...

  6. 我的Android进阶之旅------> Android为TextView组件中显示的文本添加背景色

    通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article ...

  7. linux c编程:进程控制(二)_竞争条件

    前面介绍了父子进程,如果当多个进程企图对共享数据进行处理.而最后的结果又取决于进程运行的顺序时,就认为发生了竞争关系.通过下面的例子来看下 在这里标准输出被设置为不带缓冲的,于是父子进程每输出一个字符 ...

  8. perl智能匹配

    1.perl中~~为智能匹配,它能够智能地依据符号两側的操作数来确定操作. 如要推断某个元素是否存在于数组中,不使用智能匹配,程序像这样: my $x=2; my @array=(1,2,3); my ...

  9. 更换好的yum源

    最近重装了虚拟机,因为之前总是碰到一些 yum的软件太 旧了,索性重装了 虚拟机,从零开始,然后配置yum源,以便以后安装 插件包的时候是最新的.如下: 1,进入yum源配置目录cd /etc/yum ...

  10. 牛客小白月赛1 A 简单题 【数学】

    题目链接 https://www.nowcoder.com/acm/contest/85/A 思路 这个 就是 E 但是 运算的时候 要保证 其精度 AC代码 #include <cstdio& ...