首页 > 编程语言 > 详细

"Coding Interview Guide" -- 先序、中序和后序数组两两结合重构二叉树

时间:2019-06-06 21:12:34      阅读:105      评论:0      收藏:0      [点我收藏+]

题目

  已知一棵二叉树的所有节点值都不同,给定这棵二叉树正确的先序、中序和后序数组。要求分别实现任意两种数组结合重构原来的二叉树,并返回重构二叉树的头节点

 

先序 + 中序 ==> 二叉树

  import java.util.HashMap;

1
public Node preInToTree(int[] pre, int[] in) 2 { 3 if(pre == null || in == null) 4 { 5 return null; 6 } 7 8 HashMap<Integer, Integer> map = new HashMap<>(); // 哈希表的键值对用于记录元素及其索引 9 for(int i = 0; i < in.length; i++) 10 { 11 map.put(in[i], i); 12 } 13 14 return preIn(pre, 0, pre.length - 1, in, 0, in.length - 1, map); 15 } 16 17 public Node preIn(int[] p, int pi, int pj, int[] n, int ni, int nj, HashMap<Integer, Integer> map) 18 { 19 if(pi > pj) 20 { 21 return null; 22 } 23 24 Node head = new Node(p[pi]); // 当前先序数组的第一个元素是当前子树的头节点 25 int index = map.get(p[pi]); 26 head.left = preIn(p, pi + 1, pi + index - ni, n, ni, index - 1, map); 27 head.right = preIn(p, pi + index - ni + 1, pj, n, index + 1, nj, map); 28 return head; 29 }

 

中序 + 后序 ==> 二叉树

 1 public Node inPosToTree(int[] in, int[] pos)
 2 {
 3     if(in == null || pos == null)
 4     {
 5         return null;
 6     }
 7 
 8     HashMap<Integer, Integer> map = new HashMap<>();             // 哈希表的键值对用于记录元素及其索引
 9     for(int i = 0; i < in.length; i++)
10     {
11         map.put(in[i], i);
12     }
13 
14     return inPos(in, 0, in.length - 1, pos, 0, pos.length - 1, map);
15 }
16 
17 public Node inPos(int[] n, int ni, int nj, int[] s, int si, int sj, HashMap<Integer, Integer> map)
18 {
19     if(si > sj)
20     {
21         return null;
22     }
23 
24     Node head = new Node(s[sj]);           // 当前后序数组的最后一个元素是当前子树的头节点
25     int index = map.get(s[sj]);
26     head.left = inPos(n, ni, index - 1, s, si, si + index - ni - 1, map);
27     head.right = inPos(n, index + 1, nj, s, si + index - ni, sj - 1, map);
28     return head;
29 }

 

 

来源:左程云老师《程序员代码面试指南》

"Coding Interview Guide" -- 先序、中序和后序数组两两结合重构二叉树

原文:https://www.cnblogs.com/latup/p/10986854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!