重建二叉树

解题思路

1.前序数组中的第一个为二叉树的根节点

2.根节点在中序数组中把二叉树分为左右两个子二叉树

3.根据根节点创建新的节点

4.根据中序数组确定的两个子树,分别确定下一个根节点,并分别赋值给根节点的左右节点

5.根据中序数组获得的两个子树节点结合前序遍历递归确定每一个节点

题目描述

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

代码实现

 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 = re(pre, 0, pre.length-1, in, 0, in.length-1);
13         return root;
14     }
15     
16     public TreeNode re(int [] pre, int startpre, int endpre, int [] in, int startin, int endin){
17         if(startpre>endpre||startin>endin){
18             return null;
19         }
20         TreeNode root = new TreeNode(pre[startpre]);
21         for(int i = startin; i<=endin; i++){
22             if(in[i] == pre[startpre]){
23                 root.left = re(pre, startpre+1, startpre+i-startin, in, startin, i-1);
24                 root.right = re(pre, startpre+i-startin+1, endpre, in, i+1, endin);
25             }
26         }
27         return root;
28     }
29 }
原文地址:https://www.cnblogs.com/wanglinyu/p/8331112.html