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);
}
}
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);
}
}
相关文章推荐
- Leetcode---Recover Binary Search Tree
- leetcode 99: Recover Binary Search Tree
- LeetCode:Recover Binary Search Tree
- LeetCode详细分析 :: Recover Binary Search Tree [Tree]
- LeetCode: Recover Binary Search Tree
- leetcode99---Recover Binary Search Tree(morris中序遍历恢复BST)
- leetCode_Recover Binary Search Tree
- LeetCode99 Recover Binary Search Tree
- 算法分析与设计——LeetCode Problem.99 Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- Leetcode: Recover Binary Search Tree
- [Leetcode]Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- 【LeetCode】Recover Binary Search Tree
- leetcode99 Recover Binary Search Tree java 算法
- leetcode:Recover Binary Search Tree 【Java】
- [leetcode]Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree