LeetCode Recover Binary Search Tree
来源:互联网 发布:手机遥控麻将机软件 编辑:程序博客网 时间:2024/06/05 16:07
LeetCode 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?
BST的题目一般都是和中序遍历有关,因为他中序遍历得到的一定是有序序列。
此题就是中序遍历的过程中记录出现非递增的情况,记录下非递增的2个节点,然后交换它们的数据。
//中序遍历,p1,p2分别记录出错的两个节点//p记录中序遍历时的前一个节点TreeNode* p1=NULL, *p2=NULL, *p=NULL;void recover(TreeNode* root){if(NULL == root)return ;if(root->left != NULL)recover(root->left);if(p!=NULL && root->val<p->val){if(p1 == NULL){//p1,p2是相邻节点p1 = p;p2 = root;}else{//p1和p2不相邻p2 = root;}}//中序遍历的节点记录到pp = root;if(root->right != NULL)recover(root->right);}void recoverTree(TreeNode *root) {if(NULL == root){return ;}recover(root);if(p1 && p2){int v = p1->val;p1->val = p2->val;p2->val = v;}}
0 0
- LeetCode: Recover Binary Search Tree
- LeetCode: Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [leetcode] recover binary search tree
- LeetCode -- Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- LeetCode:Recover Binary Search Tree
- [Leetcode]Recover Binary Search Tree
- Leetcode: Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- 【Leetcode】Recover Binary Search Tree
- Leetcode Recover Binary Search Tree
- LeetCode | Recover Binary Search Tree
- ubuntu安装emacs24+
- SQL2008修改表结构的时候弹出的提示. Saving changes is not permitted.
- Qt:让控件(widgets)内容可以自动 保存/读取 到配置文件(QSettings)中
- 一个免费的私有代码托管
- Python解析字符串
- LeetCode Recover Binary Search Tree
- [leetcode 27] Remove Element
- Android中自定义属性的格式详解
- 您好,2015
- [leetcode 66] Plus One
- 常见进程间通信的方式
- IOS开发中UILabel单行、多行文本计算高度、宽度的技巧
- POJ 2184 Cow Exhibition(DP)
- Class文件二进制分析