首页 > 其他 > 详细

【树】889. 根据前序和后序遍历构造二叉树

时间:2020-05-03 16:53:54      阅读:42      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

 

解答:

技术分享图片

 

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode constructFromPrePost(int[] pre, int[] post) 
12     {
13         int N = pre.length;
14         if (N == 0) 
15         {
16             return null;
17         }
18         TreeNode root = new TreeNode(pre[0]);
19         if (N == 1) 
20         {
21             return root;
22         }
23 
24         int L = 0;
25         for (int i = 0; i < N; ++i)
26             if (post[i] == pre[1])
27                 L = i+1;
28 
29         root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L+1),
30                                          Arrays.copyOfRange(post, 0, L));
31         root.right = constructFromPrePost(Arrays.copyOfRange(pre, L+1, N),
32                                           Arrays.copyOfRange(post, L, N-1));
33         return root;
34 
35     }
36 }

 

【树】889. 根据前序和后序遍历构造二叉树

原文:https://www.cnblogs.com/ocpc/p/12822078.html

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