Skip to content

Commit fce43ed

Browse files
committed
rivkode construct binary tree pre and inorder
1 parent 42340af commit fce43ed

File tree

2 files changed

+72
-21
lines changed

2 files changed

+72
-21
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
17+
import java.util.*;
18+
19+
class Solution {
20+
private int preIdx = 0;
21+
private Map<Integer, Integer> inPos = new HashMap<>();
22+
23+
public TreeNode buildTree(int[] preorder, int[] inorder) {
24+
// inorder 값의 위치를 미리 저장: value -> index
25+
for (int i = 0; i < inorder.length; i++) {
26+
inPos.put(inorder[i], i);
27+
}
28+
29+
return build(preorder, 0, inorder.length - 1);
30+
}
31+
32+
private TreeNode build(int[] preorder, int inLeft, int inRight) {
33+
// inorder 구간이 비면 서브트리 없음
34+
if (inLeft > inRight) return null;
35+
36+
// preorder에서 현재 루트 꺼내기
37+
int rootVal = preorder[preIdx++];
38+
TreeNode root = new TreeNode(rootVal);
39+
40+
// inorder에서 루트 위치 찾기
41+
int k = inPos.get(rootVal);
42+
43+
// 왼쪽 서브트리: inorder[inLeft .. k-1]
44+
root.left = build(preorder, inLeft, k - 1);
45+
46+
// 오른쪽 서브트리: inorder[k+1 .. inRight]
47+
root.right = build(preorder, k + 1, inRight);
48+
49+
return root;
50+
}
51+
}

counting-bits/rivkode.java

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -27,26 +27,26 @@ public int[] countBits(int n) {
2727
입력받은 n에 대해 toBinaryString() 을 사용하여 binaryString 값을 알아낸뒤 charAt()으로 각 인덱스별 접근하여 1의 개수를 찾아내는 방식이다.
2828
*/
2929

30-
class Solution {
31-
public int[] countBits(int n) {
32-
int[] answer = new int[n + 1];
33-
for (int i=0; i<n+1; i++) {
34-
String bit = Integer.toBinaryString(i);
35-
System.out.println(bit);
36-
int cnt = 0;
37-
for (int j=0; j < bit.length(); j++) {
38-
char c = bit.charAt(j);
39-
int num = c-'0';
40-
if (num == 1) {
41-
cnt += 1;
42-
}
43-
}
44-
45-
answer[i] = cnt;
46-
}
47-
48-
return answer;
49-
}
50-
}
30+
// class Solution {
31+
// public int[] countBits(int n) {
32+
// int[] answer = new int[n + 1];
33+
// for (int i=0; i<n+1; i++) {
34+
// String bit = Integer.toBinaryString(i);
35+
// System.out.println(bit);
36+
// int cnt = 0;
37+
// for (int j=0; j < bit.length(); j++) {
38+
// char c = bit.charAt(j);
39+
// int num = c-'0';
40+
// if (num == 1) {
41+
// cnt += 1;
42+
// }
43+
// }
44+
45+
// answer[i] = cnt;
46+
// }
47+
48+
// return answer;
49+
// }
50+
// }
5151

5252

0 commit comments

Comments
 (0)