LeetCode-Recover Binary Search Tree
2013-09-21 19:19
405 查看
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
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:
The above binary tree is serialized as
对二叉搜索树中序遍历的话应该得到一个升序序列,这个序列中两个逆序的地方就是所要找的地方。
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.
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 \ 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
对二叉搜索树中序遍历的话应该得到一个升序序列,这个序列中两个逆序的地方就是所要找的地方。
class Solution { public: void check(TreeNode* root,TreeNode** pre,TreeNode** n1,TreeNode** n2){ if(root==NULL)return ; check(root->left,pre,n1,n2); if((*pre)!=NULL&&(*pre)->val>root->val){ if((*n1)==NULL){ *n1=*pre; } *n2=root; } (*pre)=root; check(root->right,pre,n1,n2); } void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode * pre=NULL,*n1=NULL,*n2=NULL; check(root,&pre,&n1,&n2); int i=n1->val; n1->val=n2->val; n2->val=i; } };
相关文章推荐
- leetcode~Recover Binary Search Tree
- leetcode hard模式专杀之99. Recover Binary Search Tree
- leetcode---recover-binary-search-tree---树
- [leetcode-99]Recover Binary Search Tree(java)
- Leetcode Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- LeetCode99—Recover Binary Search Tree
- [leetcode] #25 Recover Binary Search Tree
- Recover Binary Search Tree -- LeetCode
- [LeetCode]Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree 解题报告
- [Leetcode] Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- 二叉树系列 - 二叉搜索树 - [LeetCode] 中序遍历中利用 pre节点避免额外空间。题:Recover Binary Search Tree,Validate Binary Search Tree
- leetcode-Recover Binary Search Tree
- leetcode 124: Recover Binary Search Tree
- leetcode_c++:树: Recover Binary Search Tree(099)
- [LeetCode] - Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- LeetCode---Recover Binary Search Tree