Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0d217c6

Browse files
author
applewjg
committed
ConstructBinaryTreefromInorderandPostorderTraversal
Change-Id: I8f6f38cc196de426c64029e825e1fe93c7f88722
1 parentecda904 commit0d217c6

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, nkuwjg@gmail.com
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+
publicclassSolution {
24+
publicTreeNodebuildTree(int[]inorder,int[]postorder) {
25+
if(inorder.length==0||postorder.length==0||inorder.length!=postorder.length)
26+
returnnull;
27+
returnbuildTreeRe(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
28+
}
29+
publicTreeNodebuildTreeRe(int[]inorder,ints1,inte1,int[]postorder,ints2,inte2){
30+
if(e2<s2)returnnull;
31+
if(s2==e2)returnnewTreeNode(postorder[e2]);
32+
intj=-1;
33+
for(inti=s1;i<=e1;i++){
34+
if(inorder[i]==postorder[e2]){
35+
j=i;
36+
break;
37+
}
38+
}
39+
intleft_len =j-s1;
40+
TreeNoderoot =newTreeNode(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+
returnroot;
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp