• 剑指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;
        }
    }
    

      

  • 相关阅读:
    什么是模块化及其优点是什么
    oop的三大特性和传统dom如何渲染
    MVC和MVVM的差别
    SpringMVC实例及注解(二)
    Spring MVC实例创建(一)
    Mybatis联合查询(一)
    Mybatis参数传递及返回类型
    Mybatis实例增删改查(二)
    Mybatis实例及配置(一)
    SpringMVC
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8530843.html
Copyright © 2020-2023  润新知