Topic:
Elements of a binary search tree (BST) is 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 about how binary tree was 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 ex Ists below.
Here's an example:
1
/\
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". Test instructions Binary lookup tree is not legal, there are two node values are exchanged, find the two nodes and do not change the structure of the tree, so that the binary lookup tree is legal, constant space constraints.
The main point of this problem is to think of using the recursive middle sequence traversal of the tree, because the binary search tree is a valid case, the value of the middle sequence traversal is from small to large arrangement.
When the current value is smaller than the previous value, there is an illegal node.
With the pre-stored in the sequence of the current node in the previous node, the convenient value of the size of the comparison, with S1,S2 record the location of the two illegal sequences, s1 large values, s2 save a smaller value.
Finally, the two illegal values are exchanged.
/**
* 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 *s1,*s2,*pre;
void hehe (TreeNode *root)
{
if (!root) return;
Hehe (root->left);
if (pre&& pre->val > Root->val)
{
if (s1==null) s1=pre,s2=root;
else s2=root;
}
Pre=root;
Hehe (root->right);
}
void Recovertree (TreeNode *root) {
if (!root) return;
S1=s2=pre=null;
hehe (root);
Swap (S1->val,s2->val);
}
};
Http://blog.csdn.net/havenoidea
Catalog