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

Leetcode-Construct Binary Tree from inorder and preorder travesal

时间:2014-11-29 01:31:14      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   strong   on   

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

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

Solution:

 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         TreeNode root = buildTreeRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
13         return root;
14     }
15 
16     public TreeNode buildTreeRecur(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE){
17         if (preS>preE) return null;
18         if (preS==preE){
19             TreeNode leaf = new TreeNode(preorder[preS]);
20             return leaf;
21         }
22 
23         int rootVal = preorder[preS];
24         int index = inS;
25         for (int i=inS;i<=inE;i++)
26             if (inorder[i]==rootVal){
27                 index = i;
28                 break;
29             }
30 
31         int leftLen = index-inS;
32         int rightLen = inE - index;
33    
34         TreeNode leftChild = buildTreeRecur(preorder,inorder,preS+1,preS+leftLen,inS,index-1);
35         TreeNode rightChild = buildTreeRecur(preorder,inorder,preE-rightLen+1,preE,index+1,inE);
36         TreeNode root = new TreeNode(rootVal);
37         root.left = leftChild;
38         root.right= rightChild;
39         return root;
40    }
41       
42 }

 

Construct Binary Tree from Preorder and Inorder Traversal

Leetcode-Construct Binary Tree from inorder and preorder travesal

标签:style   blog   io   ar   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4129712.html

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