Question
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Code
TreeNode pre = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
inOrder(root);
int tmp = first.val;
first.val = second.val;
second.val = tmp;
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
if (pre != null && pre.val > root.val) {
if (first == null) {
first = pre;
second = root;
} else {
second = root;
}
}
pre = root;
inOrder(root.right);
}
本文介绍了一种解决二叉搜索树中两个节点被错误交换的问题的方法。通过中序遍历找到这两个节点,并交换它们的值,从而在不改变树结构的情况下恢复二叉搜索树的性质。
3349

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



