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

Commitc25f01b

Browse files
authored
Create Construct Binary Tree from Preorder and Postorder Traversal.java
1 parentc1ff60a commitc25f01b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
classSolution {
17+
publicTreeNodeconstructFromPrePost(int[]preorder,int[]postorder) {
18+
intn =preorder.length;
19+
Map<Integer,Integer>postorderIndex =newHashMap<>();
20+
for (inti =0;i <n;i++) {
21+
postorderIndex.put(postorder[i],i);
22+
}
23+
returnconstructTree(0,n -1,0,preorder,postorderIndex);
24+
}
25+
26+
privateTreeNodeconstructTree(intpreStart,intpreEnd,intpostStart,int[]preorder,Map<Integer,Integer>postorderIndex) {
27+
if (preStart >preEnd) {
28+
returnnull;
29+
}
30+
if (preStart ==preEnd) {
31+
returnnewTreeNode(preorder[preStart]);
32+
}
33+
intleftRoot =preorder[preStart +1];
34+
intleftCount =postorderIndex.get(leftRoot) -postStart +1;
35+
TreeNoderoot =newTreeNode(preorder[preStart]);
36+
root.left =constructTree(preStart +1,preStart +leftCount,postStart,preorder,postorderIndex);
37+
root.right =constructTree(preStart +leftCount +1,preEnd,postStart +leftCount,preorder,postorderIndex);
38+
returnroot;
39+
}
40+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp