您的位置:首页 > 编程语言 > Java开发

LeetCode | Recover Binary Search Tree

2014-03-02 10:58 267 查看
题目

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?
分析

根据对BST中序遍历结果的升序特性,可以找到逆序对,这里要注意两种情况:

1. 如果交换节点刚好在中序遍历时,是相邻的,那么只有一个逆序对;

2. 如果不相邻,就有两个逆序对

代码

public class RecoverBinarySearchTree {
private TreeNode first;
private TreeNode second;
private TreeNode preNode;

public void recoverTree(TreeNode root) {
first = null;
second = null;
preNode = null;
inorder(root);
assert first != null && second != null;
int temp = first.val;
first.val = second.val;
second.val = temp;
}

private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
if (preNode != null && root.val < preNode.val) {
if (first == null) {
first = preNode;
}
second = root;
}
preNode = root;
inorder(root.right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 递归