树的算法 已知二叉树的前序序列和中序序列求解树

题目: 已知二叉树的前序序列和中序序列求解树

比如

    6

  4    8

3  5   7

前序序列为6,4,3,5,8,7

中序序列为3,4,5,6,7,8

思路: 前序遍历序列的第一个元素必为根节点 则中序遍历序列中,该节点之前的为左子树,该节点之后的为右子树,若该节点之前没有节点,则左子树为空,反之右子树为空,

截取个子树的前序和中序序列,重复上述逻辑递归求解

 

我自己的思路是只根据前序遍历序列也可得到:同理前序第一个元素为根节点,向后依次比较后续元素,直到找到第一个比根元素大的,则该元素与根元素之间的所有元素(不包括)为左子树,该元素之后的所有元素(包括)为右子树,对子树使用相同逻辑递归即可,但需要判断子树为空的情况 

 

 1 package com.rui.microsoft;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Tree_BuildTreeByPreMid {
 6 
 7     public static void main(String[] args) {
 8         
 9         int[] pre = {6,4,3,5,8,7};
10         //int[] mid = {3,4,5,6,7,8};
11         
12         Node root = Tree_BuildTreeByPreMid.build(pre);
13         System.out.println(root.value);
14     }
15     
16     public static Node build(int[] pre){
17         int rootV = pre[0];
18         Node root = new Node(rootV);
19         
20         int left = 1;
21         while(left < pre.length && pre[left] < rootV) left++;
22         
23         //No left tree, because the pointer left has not changed
24         if(left == 1){
25             root.left = null;
26         }else{
27             int[] leftArray = Arrays.copyOfRange(pre, 1, left);
28             root.left = build(leftArray);
29         }
30         
31         //No right tree, because the pointer left has been moved to the end of the array
32         if(left == pre.length){
33             root.right = null;
34         }else{
35             int[] rightArray = Arrays.copyOfRange(pre, left, pre.length);
36             root.right = build(rightArray);
37         }
38         
39         return root;
40     }
41     
42     static class Node {
43         int value;
44         Node left;
45         Node right;
46         public Node(int v){
47             this.value = v;
48         }
49     }
50 }

 

posted @ 2015-10-23 16:02  蟹粉小笼包  阅读(3057)  评论(0编辑  收藏  举报