您的位置:首页 > 其它

LeetCode 99. Recover Binary Search Tree(修复二叉搜索树)

2016-05-23 00:39 351 查看
原题网址:https://leetcode.com/problems/recover-binary-search-tree/

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?

方法一:发现有错误顺序则交换,知道全部正确。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<TreeNode> errors = new ArrayList<>();
private int min(TreeNode root) {
if (root.left != null) return min(root.left);
return root.val;
}
private int max(TreeNode root) {
if (root.right != null) return max(root.right);
return root.val;
}
private TreeNode rightmost(TreeNode root) {
if (root.right != null) return rightmost(root.right);
return root;
}
private TreeNode leftmost(TreeNode root) {
if (root.left != null) return leftmost(root.left);
return root;
}
boolean swapped = false;
private void swap(TreeNode node1, TreeNode node2) {
int temp = node1.val;
node1.val = node2.val;
node2.val = temp;
swapped = true;
}
private void check(TreeNode root) {
if (root.left != null) {
if (root.left.val >= root.val) {
swap(root, root.left);
}
check(root.left);
if (max(root.left) >= root.val) {
TreeNode rightmost = rightmost(root.left);
swap(root, rightmost);
}
}
if (root.right != null) {
if (root.right.val <= root.val) {
swap(root, root.right);
}
check(root.right);
if (min(root.right) <= root.val) {
TreeNode leftmost = leftmost(root.right);
swap(root, leftmost);
}
}
}
public void recoverTree(TreeNode root) {
do {
swapped = false;
check(root);
} while (swapped);
}
}


方法二:分析两种错误。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private void swap(TreeNode n1, TreeNode n2) {
int t = n1.val;
n1.val = n2.val;
n2.val = t;
}

private TreeNode[] errors = new TreeNode[4];
private int count;
private TreeNode prev;
private void check(TreeNode root) {
if (count == 4) return;
if (root.left != null) check(root.left);
if (prev != null && prev.val > root.val) {
errors[count++] = prev;
errors[count++] = root;
}
prev = root;
if (root.right != null) check(root.right);
}

public void recoverTree(TreeNode root) {
check(root);
if (count == 2) swap(errors[0], errors[1]);
else swap(errors[0], errors[3]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: