zoukankan      html  css  js  c++  java
  • 剑指offer——重建二叉树

    重建二叉树

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            
        }
    }
    

      

    自己写的不对,在传入左右子树的范围那里  preLeft + i - inLeft  为什么不能直接是 i

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            TreeNode tree = subTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
            return tree;
        }
        public TreeNode subTree(int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight){
            if(preLeft > preRight || inLeft > inRight) return null;
    
            TreeNode subRoot = new TreeNode(pre[preLeft]);
            for(int i = 0; i < in.length; ++i){
                if(in[i] == pre[preLeft]){
                    subRoot.left = this.subTree(pre, preLeft + 1, preLeft + i - inLeft, in, inLeft, i - 1);
                    subRoot.right = this.subTree(pre, preLeft + i - inLeft + 1, preRight, in, i + 1, inRight);
                    break;
                }
            }
            return subRoot;
        }
    }
    

      

  • 相关阅读:
    Apache日志分析
    iptables日志探秘
    php与其他一些相关工具的安装步骤分享
    ERROR 1 (HY000): Can't create/write to file '/tmp/#sql_830_0.MYI' (Errcode: 13)
    一些可能需要的正则
    restful api的简单理解
    认识MySQL Replication
    如何处理缓存失效、缓存穿透、缓存并发等问题
    经典算法mark
    php常用的一些代码
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8530843.html
Copyright © 2011-2022 走看看