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

leetcode------Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-03-11 23:14:51      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

标题:

Construct Binary Tree from Preorder and Inorder Traversal

通过率: 26.5
难度:  中等

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

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

根据前序遍历和中序遍历构建二叉树:看一棵树如下:

    1
   /   2   4
   \      5    6
前序为:12546
中序为:25146


从前序得知第一个数一定是树的root,通过中序得到右树和左树

递归调用即可,其中要注意递归的条件个字符串拷贝时的用法,

具体看代码

 

 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 buildTree(int[] preorder, int[] inorder) {
12         if(preorder.length==0||inorder.length==0){
13             return null;
14         }
15         TreeNode root=new TreeNode(preorder[0]);
16         int i=0;
17         for(;i<inorder.length;i++){
18             if(inorder[i]==preorder[0])break;
19         }
20         int [] new_pre_left,new_pre_right,new_in_left,new_in_right;
21         if(i<preorder.length){
22             new_in_left=new int[i];
23             System.arraycopy(inorder, 0, new_in_left, 0, i); 
24             new_pre_left=new int[i];
25             System.arraycopy(preorder, 1, new_pre_left, 0, i);  
26             root.left=buildTree(new_pre_left,new_in_left);
27             
28             new_in_right=new int[preorder.length-i-1];
29             System.arraycopy(inorder, i+1, new_in_right, 0, preorder.length-i-1); 
30             new_pre_right=new int[preorder.length-i-1];
31              System.arraycopy(preorder, i+1, new_pre_right, 0, preorder.length-i-1); 
32              root.right=buildTree(new_pre_right,new_in_right);
33             
34         }
35         return root;
36     }
37 }

 

leetcode------Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4331096.html

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