【剑指offer】7.重建二叉树

在这里插入图片描述

   *
     * 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 root = reConstructTreecode(
                pre,0,pre.length-1,in,0,in.length-1);
            return root;
        }
        public static TreeNode reConstructTreecode(
            int[] pre,int startpre,int endpre,int[] in,int startin,int endin){
            if(startpre>endpre||startin>endin)
                return null;
            TreeNode root = new TreeNode(pre[startpre]);
            for(int i=startin;i<=endin;i++){
                if(in[i]==pre[startpre]){
                root.left=reConstructTreecode(pre,startpre+1,startpre+i-startin,in,startin,i-1);
                root.right=reConstructTreecode(pre,startpre+i-startin+1,endpre,in,i+1,endin);
                }
            }
            return root;
        }
    }

猜你喜欢

转载自blog.csdn.net/beauman/article/details/89526669