修复二叉查找树 Recover Binary Search Tree
来源:互联网 发布:劳尔实况巅峰数据 编辑:程序博客网 时间:2024/06/05 19:35
问题:给出一个有问题的二叉查找树,其中有一对儿结点上的数字弄反了。要求把它俩找出来并恢复到正常的二叉查找树。
思路:正常的二叉查找树,中序遍历应该是递增序列。现在有一对数被交换了。那么中序序列中必定先遇到一个比其右边的数要大的数,然后再遇到一个比起左边的数小的数。
这两个数就是应该被交换回来的数。
比如交换两个不相邻的数 1 2 3 4 5,交换成 1 4 3 2 5,会发现两个降序:4到3为降序,3到2为降序。
比如交换两个相邻的数 1 2 3 4 5,交换成1 3 2 4 5,会发现一个降序:3降到2。
因此可能有两种情况。
代码:使用全局变量保存递归过程中发现的降序。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<TreeNode *> rem; void recoverTree(TreeNode *root) { if(root == NULL) return; TreeNode *last = NULL; find(root, last); if(rem.size() == 4)//交换的数不相邻 { swap(rem[0]->val, rem[3]->val); } else //交换的数相邻 { swap(rem[0]->val, rem[1]->val); } } //last参数保存中序遍历的上一个结点 void find(TreeNode* root, TreeNode* &last) { if(root->left != NULL) find(root->left, last); if(last != NULL && last->val > root->val) { rem.push_back(last); rem.push_back(root); } last = root;//更新last if(root->right != NULL) find(root->right, last); } void swap(int &a, int &b) { int tmp; tmp = a; a = b; b = tmp; }};
0 0
- 修复二叉查找树 Recover Binary Search Tree
- Recover Binary Search Tree 修正二叉查找树
- 【修正二叉树】Recover Binary Search Tree
- 二叉树-recover binary search tree
- LeetCode 99. Recover Binary Search Tree(修复二叉搜索树)
- [leetcode-二叉查找树的修正]--99. Recover Binary Search Tree
- Recover Binary Search Tree(恢复二叉搜索树)
- LeetCode | Recover Binary Search Tree(恢复二叉搜索树)
- LeetCode-99-Recover Binary Search Tree 二叉树交换结点
- 二叉查找树(Binary Search Tree)
- 二叉查找树(Binary Search Tree)
- 二叉查找树(Binary Search Tree)
- 二叉查找树(binary search tree)详解
- BST(Binary Search Tree) 二叉查找树
- Binary Search Tree 二叉查找树
- 二叉查找树(Binary Search Tree)
- leetcode:Recover Binary Search Tree (修正二叉查找树错误节点,不改变结构)【面试算法题】
- 99. Recover Binary Search Tree 将二叉查找树中乱序的两个元素值调整
- 【marks】Unity3D
- casio计算器fx82es刷机实现十进制转其他进制的模式
- cocos2d-x 框架深入分析 - MainLoop
- 十大新兴云操作系统
- hdu 2114 Calculate S(n)(找规律的题目,比赛的时候没做出来)
- 修复二叉查找树 Recover Binary Search Tree
- Unity3d中使用Lua
- java封装类(二)
- 前端之Android入门(3):MVC模式(上)
- 游戏动态
- 人生总会遇到浑噩期,但是需要反思
- 车票找零
- Oracle中Hint深入理解
- IOS-播放沙盒目录及本地音频文件