zoukankan      html  css  js  c++  java
  • [leedcode 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?

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        TreeNode firstNode;
        TreeNode secondNode;
        TreeNode pre;
        public void recoverTree(TreeNode root) {
            //对于二叉搜索树来讲,中序遍历应该是递增的,本题要求O(1)空间,出发点就是中序遍历的变形
            //在中序遍历的过程中,需要找到fisrtWrongNode和secondWrongNode,本题最主要的是,使用pre全局遍历,
            /*递归的时候使得pre=root,达到pre能够保存root前置节点的作用,通过比较root和pre的值,找到逆序对,
            如果两个数相邻置换,则逆序对只有一个,
            如果两个数不相邻,逆序对有两个,此时需要更新secondWrongNode*/
            if(root==null) return;
            inOrder(root);
            swap(firstNode,secondNode);
        }
        public void inOrder(TreeNode root){
            if(root==null) return;
            inOrder(root.left);
           /* if(pre!=null&&firstNode==null&&root.val<pre.val){
                firstNode=pre;
            }
            if(pre!=null&&firstNode!=null&&root.val<pre.val){
                secondNode=root;
            }可被下面一个if语句替换*/
            if(pre!=null&&root.val<pre.val){
                if(firstNode==null) firstNode=pre;
                secondNode=root;
            }
    
            pre=root;
            inOrder(root.right);
        }
        public void swap(TreeNode s1,TreeNode s2){
            int temp=s1.val;
            s1.val=s2.val;
            s2.val=temp;
        }
    }
  • 相关阅读:
    Two strings CodeForces
    Dasha and Photos CodeForces
    Largest Beautiful Number CodeForces
    Timetable CodeForces
    Financiers Game CodeForces
    AC日记——整理药名 openjudge 1.7 15
    AC日记——大小写字母互换 openjudge 1.7 14
    AC日记——将字符串中的小写字母换成大写字母 openjudge 1.7 13
    AC日记——加密的病历单 openjudge 1.7 12
    AC日记——潜伏着 openjudge 1.7 11
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4652797.html
Copyright © 2011-2022 走看看