您的位置:首页 > 其它

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
"{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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: