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?
思路;递归。使用递归查找左子树的最大节点,使用递归查找右子树的最小节点;
1若左子树的最大节点的值比右子树的最小节点大,说明是左子树的最大节点与右子树的最小节点进行了交换;
2若若左子树的最大节点的值比根节点大,说明是根节点与左子树的最大节点进行了交换;
3若若右子树的最大节点的值比根节点小,说明是根节点与右子树的最小节点进行了交换;
4若上述三种情况均没有发生,则说明左子树的某两个节点进行了交换或者右子树的某两个节点进行了交换,递归查看左子树和右子树是否有节点进行了交换;
public class Solution {
private TreeNode findMin(TreeNode root) {
TreeNode result, l = root, r = root;
if (root.left != null)
l = findMin(root.left);
if (root.right!= null)
r = findMin(root.right);
result = l.val < r.val ? l : r;
return result.val < root.val ? result : root;
}
private TreeNode findMax(TreeNode root) {
TreeNode result, l = root, r = root;
if (root.left != null)
l = findMax(root.left);
if (root.right != null)
r = findMax(root.right);
result = l.val > r.val ? l : r;
return result.val > root.val ? result : root;
}
public void recoverTree(TreeNode root) {
TreeNode l=root,r=root;
if(root==null||(root.left==null&&root.right==null)) return;
if(root.left!=null) l=findMax(root.left);
if(root.right!=null) r=findMin(root.right);
if(l.val>r.val){
int temp=l.val;
l.val=r.val;
r.val=temp;
return ;
}else if(l.val>root.val){
int temp=l.val;
l.val=root.val;
root.val=temp;
return ;
}else if(r.val<root.val){
int temp=r.val;
r.val=root.val;
root.val=temp;
return ;
}else{
recoverTree(root.left);
recoverTree(root.right);
}
}
}LeetCode 99 Recover Binary Search Tree
原文地址:http://blog.csdn.net/mlweixiao/article/details/38929785