zoukankan      html  css  js  c++  java
  • Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Ref:http://fisherlei.blogspot.com/2012/12/leetcode-recover-binary-search-tree.html

    O(1)的解法就是
    Inorder traverse, keep the previous tree node,
    Find first misplaced node by
    if ( current.val < prev.val )
       Node first = prev;

    Find second by
    if ( current.val < prev.val )
       Node second = current;

    After traversal, swap the values of first and second node. Only need two pointers, prev and current node. O(1) space.

    但是这个解法的前提是Traverse Tree without Stack. 中序遍历如何才能不使用栈。这里就要引入一个概念, Threaded Binary Tree。So, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.

    1. Initialize current as root 
    2. While current is not NULL
       If current does not have left child
          a) Print current’s data
          b) Go to the right, i.e., current = current->right
       Else
          a) Make current as right child of the rightmost node in current's left subtree
          b) Go to this left child, i.e., current = current->left
    public class Solution {
        public void recoverTree(TreeNode root) {
            TreeNode f1 = null, f2 = null;
            TreeNode current, pre, parent = null;
    
           if(root == null)
                 return;
           // 用来记录是第几次找到bad node, 因为第一次找到的bad node为cur.pre,第二次找到bad node是cur
           boolean found = false;
           current = root;
           while(current != null)
           {                
                 if(current.left == null)
                 {
                        if(parent != null && parent.val > current.val)
                        {
                               if(!found)
                               {
                                     f1 = parent;
                                     found = true;
                               }
                               f2 = current;
                        }
                        parent = current;
                        current = current.right;     
                 }   
                 else
                 {
                        /* Find the inorder predecessor of current */
                        pre = current.left;
                        while(pre.right != null && pre.right != current)
                               pre = pre.right;
    
                        /* Make current as right child of its inorder predecessor */
                        if(pre.right == null)
                        {
                               pre.right = current;
                               current = current.left;
                        }
    
                        /* Revert the changes made in if part to restore the original
                        tree i.e., fix the right child of predecssor */  
                        else
                        {
                          // 注意跳进这里的原因是,当把root 设为左子树的最右节点时,root.left 仍然为左子树的根节点,相当于生成了一个环
                               pre.right = null;
                               if(parent.val > current.val)
                               {
                                     if(!found)
                                     {
                                            f1 = parent;       
                                            found = true;
                                     }
                                     // f2 不写在else里的原因是 有可能是相邻的两个元素交换了
                                     f2 = current;
                               }
                               parent = current;
                               current = current.right;     
                        } /* End of if condition pre->right == NULL */
                 } /* End of if condition current->left == NULL*/
           } /* End of while */
    
           if(f1 != null && f2 != null){
               int tmp = f1.val;
               f1.val = f2.val;
               f2.val = tmp;
           }
                 
        }
    }        
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public static void recoverTree(TreeNode root) {
            ArrayList<TreeNode> inorderList = new ArrayList<TreeNode>();
            inorder(root, inorderList);
            int first= -1, second  = -1; 
            boolean secondNumber = false;
            for(int i = 1; i < inorderList.size();i++){
                if (inorderList.get(i-1).val > inorderList.get(i).val){
                    if(!secondNumber){
                        first = i-1;
                        second = i;
                        secondNumber = true;
                    }else{
                        second = i;
                    }
                }
            }
            swap(inorderList.get(first), inorderList.get(second));
        }
        
        private static void inorder(TreeNode root, ArrayList<TreeNode> inorderList){
            if(root != null){
                inorder(root.left, inorderList);
                inorderList.add(root);
                inorder(root.right, inorderList);
            }
        }
        
        private static void swap(TreeNode i, TreeNode j){
            int tmp = i.val;
            i.val = j.val;
            j.val = tmp;
        }
        
    }
  • 相关阅读:
    设计模式学习笔记之一:策略模式
    向上转型和向下转型
    html readonly和disabled的区别
    如何自定义JSR-303标准的validator
    vue 组件属性props,特性驼峰命名,连接线使用
    laydate中设置动态改变max与min值的方法
    浅谈JS中 reduce() 的用法
    jq 实时监听input输入框的变化
    npm install --save 和 npm install -d的区别
    vue中html、js、vue文件之间的简单引用与关系
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3557776.html
Copyright © 2011-2022 走看看