您的位置:首页 > 其它

[LeetCode] Recover Binary Search Tree

2013-08-27 21:32 411 查看
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?

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* w1,*w2;
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

w1=NULL;
w2=NULL;
TreeNode* pre=NULL;
inorder(root,pre);

assert(w1&&w2);
swap(w1->val,w2->val);
}
void inorder(TreeNode* root,TreeNode*& pre)
{
if (!root )
return ;
inorder(root->left,pre);
if (pre&& pre->val>=root->val)
{
if (w1==NULL)
{
w1=pre;
w2=root;
}
else
{
w2=root;
}
}
pre=root;
inorder(root->right,pre);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: