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

Commit 71ddb3a

Browse files
Add Solution2.java to problems 0105
1 parent 03fbbe6 commit 71ddb3a

File tree

1 file changed

+36
-0
lines changed
  • solution/0105.Construct Binary Tree from Preorder and Inorder Traversal

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
12+
private int idx;
13+
private int[] preorder;
14+
private Map<Integer, Integer> map = new HashMap<>();
15+
16+
public TreeNode buildTree(int[] preorder, int[] inorder) {
17+
this.idx = 0;
18+
this.preorder = preorder;
19+
int index = 0;
20+
for (int value : inorder) {
21+
map.put(value, index ++);
22+
}
23+
return buildTree(0, inorder.length);
24+
}
25+
26+
private TreeNode buildTree(int left, int right) {
27+
if (left >= right) return null;
28+
int rootVal = preorder[idx ++];
29+
int index = map.get(rootVal);
30+
31+
TreeNode root = new TreeNode(rootVal);
32+
root.left = buildTree(left, index);
33+
root.right = buildTree(index + 1, right);
34+
return root;
35+
}
36+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /