您的位置:首页 > 其它

99. Recover Binary Search Tree

2017-05-15 13:51 393 查看
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?

Subscribe to see which companies asked this question.

这道题目要实现二叉搜索树的两个错误节点的恢复(是在O(n)的空间范围内),首先使用中序遍历找到两个错误的节点,使用一个list的空间代价为O(n),然后再将两个节点的val交换即可,不需要交换两个节点。具体代码如下:

public void recoverTree(TreeNode root) {//针对二叉搜索树
//两个节点顺序错误,现在要重新交换两个错误节点,但是不改变树的结构
if(root==null) return;
ArrayList<TreeNode> list=new ArrayList<>();
In_Order_Tree(root,list);
int begin,end;
for ( begin = 0; begin < list.size()-1; begin++) {
if (list.get(begin).val>list.get(begin+1).val) {
break;
}
}
for ( end = list.size()-1; end >=0; end--) {
if (list.get(end).val<list.get(end-1).val) {
break;
}
}
int temp=list.get(begin).val;
list.get(begin).val=list.get(end).val;
list.get(end).val=temp;

}
private static void In_Order_Tree (TreeNode root,ArrayList<TreeNode> list) {
if (root!=null) {
In_Order_Tree(root.left, list);
list.add(root);
In_Order_Tree(root.right, list);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: