Skip to content

Commit 0d217c6

Browse files
author
applewjg
committed
ConstructBinaryTreefromInorderandPostorderTraversal
Change-Id: I8f6f38cc196de426c64029e825e1fe93c7f88722
1 parent ecda904 commit 0d217c6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Author: Andy, [email protected]
3+
Date: Jan 16, 2015
4+
Problem: Construct Binary Tree from Inorder and Postorder Traversal
5+
Difficulty: Easy
6+
Source: http://leetcode.com/onlinejudge#question_106
7+
Notes:
8+
Given inorder and postorder traversal of a tree, construct the binary tree.
9+
Note:
10+
You may assume that duplicates do not exist in the tree.
11+
12+
Solution: Recursion.
13+
*/
14+
/**
15+
* Definition for binary tree
16+
* public class TreeNode {
17+
* int val;
18+
* TreeNode left;
19+
* TreeNode right;
20+
* TreeNode(int x) { val = x; }
21+
* }
22+
*/
23+
public class Solution {
24+
public TreeNode buildTree(int[] inorder, int[] postorder) {
25+
if(inorder.length==0||postorder.length==0||inorder.length!=postorder.length)
26+
return null;
27+
return buildTreeRe(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
28+
}
29+
public TreeNode buildTreeRe(int[] inorder,int s1,int e1, int[] postorder, int s2,int e2){
30+
if(e2<s2) return null;
31+
if(s2==e2) return new TreeNode(postorder[e2]);
32+
int j=-1;
33+
for(int i=s1;i<=e1;i++){
34+
if(inorder[i]==postorder[e2]){
35+
j=i;
36+
break;
37+
}
38+
}
39+
int left_len = j-s1;
40+
TreeNode root = new TreeNode(postorder[e2]);
41+
root.left = buildTreeRe(inorder,s1,j-1,postorder,s2,s2+left_len-1);
42+
root.right = buildTreeRe(inorder,j+1,e1,postorder,s2+left_len,e2-1);
43+
return root;
44+
}
45+
}

0 commit comments

Comments
 (0)