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

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

解题思路:

像这种题首选递归来做,一个大的数组拆分成不同的区域来做。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode reConstructBinaryTree(int[] pre,int[] in) {
12         TreeNode root = reConstruct(pre,0,pre.length-1,in,0,in.length-1);
13         return root;
14     }
15     private TreeNode reConstruct(int [] pre, int startpre,int endpre,int [] in, int startin,int endin)
16    {
17        if(startpre>endpre || startin>endin)
18        {
19            return null;
20        }
21        
22        TreeNode root = new TreeNode (pre[startpre]);
23        
24        for(int i=startin; i<=endin;i++)
25        {
26            if(in[i]==pre[startpre])
27            {
28                root.left = reConstruct(pre,startpre+1,startpre+i-startin,in,startin,i-1);
29                root.right = reConstruct(pre,startpre+i-startin+1,endpre,in,i+1,endin);
30                
31            }
32        }
33        return root;
34        
35    }
36        
37         
38         
39 }

 

 根据前序和中序重建二叉树 随笔

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄