【修正二叉树】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?

题意:二叉搜索树中有两个节点的值交换,在不修改二叉树的结构的前提下修正该树

O(n)空间的算法是用中序遍历求出二叉树的现有顺序存在一个新数组中,再进行排序,最后将排序后的值重新赋给原树,这种方法通用n个节点错乱的情况。

O(1)空间算法:中序遍历的过程中用两个指针来找寻混乱的两个节点,思路参考http://blog.csdn.net/havenoidea/article/details/12869021

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private TreeNode s1=null, s2=null, pre=null;
    public void inorder(TreeNode root){
        if(root != null){
            inorder(root.left);
            if(pre!=null && pre.val > root.val){
                if(s1 == null){
                    s1 = pre;//异常的第一个节点
                }
                s2 = root;//异常的第二个节点
            }
            pre = root;
            inorder(root.right);
        }
    }
    
    public void recoverTree(TreeNode root) {
        inorder(root);
        int t = s1.val;
        s1.val = s2.val;
        s2.val = t;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值