码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode105:Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-07-03 13:05:43      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

解题思路分析:

前序遍历首先遍历根节点,然后依次遍历左右子树

中序遍历首先遍历左子树,然后遍历根结点,最后遍历右子树

根据二者的特点,前序遍历的首节点就是根结点,然后在中序序列中找出该结点位置(index),则该结点之前的为左子树结点,该节点之后为右子树结点;

同样对于前序序列,首结点之后的index个结点为左子树结点,剩余的节点为右子树结点;

最后,递归建立子树即可。

 

java代码:

 1 public class Solution {
 2     public TreeNode buildTree(int[] preorder, int[] inorder) {
 3         if(preorder == null || preorder.length == 0){
 4             return null;
 5         }
 6         
 7         int flag = preorder[0];
 8         TreeNode root = new TreeNode(flag);
 9         int i = 0;
10         for(i=0; i<inorder.length; i++){
11             if(flag == inorder[i]){
12                 break;
13             }
14         }
15         
16         int[] pre_left, pre_right, in_left, in_right;
17         pre_left = new int[i];
18         for(int j=1; j<=i;j++){
19             pre_left[j-1] = preorder[j];
20         }
21         pre_right = new int[preorder.length-i-1];
22         for(int j=i+1; j<preorder.length;j++){
23             pre_right[j-i-1] = preorder[j];
24         }
25         
26         in_left = new int[i];
27         for(int j=0;j<i;j++){
28             in_left[j] = inorder[j];
29         }
30         in_right = new int[inorder.length-i-1];
31         for(int j=i+1; j<inorder.length; j++){
32             in_right[j-i-1] = inorder[j];
33         }
34         root.left = buildTree(pre_left,in_left);
35         root.right = buildTree(pre_right,in_right);
36         
37         
38         
39         return root;
40         
41     }
42     
43    
44 }

 

leetcode105:Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/bywallance/p/5637787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!