leetCode 99. 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?

1将二叉搜索树中两个元素调换了位置,现在要把二叉搜索树还原成有序。
2首先二叉搜索树有个性质是,对其中序遍历时,得到的序列一定是有序的。
3那么用中序遍历,看得到的序列中乱序的数,然后将其交换
4要求用常数空间,那么用pre指针记录下乱序之处即可
5乱序的情况有两种,只有一处乱序,那么直接交换;还有两处乱序的情况:比如按中序遍历s1,s2,s3,s4;先后发现s1>s2 ,s3>s4,那么就要把s1和s4交换

  public static int count=0;
     public static TreeNode temp1=null;
     public static TreeNode temp2=null;
     public static TreeNode temp1Pre=null;
     public static TreeNode cur=null;
     public static TreeNode pre=null;

        public static void recoverTree(TreeNode root) {
            if(root==null)return;
             count=0;
         temp1=null;
         temp2=null;
         temp1Pre=null;
         cur=null;
         pre=null;
            recoverTree2(root);
            if(count==1){
                int temp = temp1.val;
                temp1.val = temp1Pre.val;
                temp1Pre.val = temp;
            }
            else if(count==2){
                int temp = temp1Pre.val;
                temp1Pre.val = temp2.val;
                temp2.val = temp;
            }
        }

        public static void recoverTree2(TreeNode root) {
            if(root==null)return;

            if(root.left!=null){
                recoverTree2( root.left);

            }

            if(pre!=null){
                if(pre.val>root.val){
                    if(count==0){
                        temp1=root;
                        temp1Pre=pre;

                    }
                    else if(count==1){
                        temp2=root;
                    }
                    count++;
                }
            }



            if(root.right!=null){
                pre=root;
                recoverTree2( root.right);
            }
            //子节点遍历完,那么如果有root.right,则pre就为上一次pre,否则为root
            if(root.right==null){
                pre=root;
            }



        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值