[LeetCode] 078: Recover Binary Search Tree
来源:互联网 发布:点餐系统数据库设计 编辑:程序博客网 时间:2024/05/21 11:17
[Problem]
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
OJ's Binary Tree Serialization:
[Solution]
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?
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
. [Solution]
/**说明:版权所有,转载请注明出处。Coder007的博客
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode *root, TreeNode* &pre, TreeNode* &first, TreeNode* &second){
if(NULL == root)return ;
// visit the left brunch
inorder(root->left, pre, first, second);
// visit the root
if(pre != NULL && pre->val > root->val){
if(first == NULL){
first = pre;
}
second = root;
}
pre = root;
// visit the right brunch
inorder(root->right, pre, first, second);
}
void recoverTree(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(NULL == root)return;
// initial
TreeNode* pre = NULL;
TreeNode* first = NULL;
TreeNode* second = NULL;
// inorder
inorder(root, pre, first, second);
if(first != NULL && second != NULL){
first->val ^= second->val;
second->val ^= first->val;
first->val ^= second->val;
}
}
};
阅读全文
0 0
- [LeetCode] 078: 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
- [转载] 从Trie树到后缀树
- 薛定谔的猫
- Windows python3下安装scrapy爬虫框架的完美方案
- [面试题] 随机数相关面试题(1)
- [面试题] 随机数相关面试题(2)
- [LeetCode] 078: Recover Binary Search Tree
- 下拉刷新,上拉加载
- [LeetCode] 079: Regular Expression Matching
- hdu 6198 number number number
- [LeetCode] 080: Remove Duplicates from Sorted Array
- [LeetCode] 081: Remove Duplicates from Sorted Array II
- [LeetCode] 082: Remove Duplicates from Sorted List
- [LeetCode] 083: Remove Duplicates from Sorted List II
- [LeetCode] 084: Remove Element