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.
void help(TreeNode* root, TreeNode* &pre, TreeNode*&first, TreeNode*&second){
if (root == NULL)
return;
help(root->left,pre, first, second);
if (pre == NULL)
pre = root;
else{
if (pre->val > root->val){
if (first == NULL){
first = pre;
second = root;
}
else{
second = root;
return;
}
}
pre = root;
}
help(root->right, pre, first, second);
}
void recoverTree(TreeNode *root) {
TreeNode* pre = NULL;
TreeNode* first = NULL, *second = NULL;
if (root == NULL)
return;
help(root, pre, first, second);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}

本文介绍了一种常数空间解决方案,用于在二叉搜索树中找到并修复由错误交换导致的位置不正确的节点,通过中序遍历来定位问题节点并进行交换。

3628

被折叠的 条评论
为什么被折叠?



