Skip to content

Commit dfc9971

Browse files
committed
[Week2](gmlwls96) construct binary tree from preorder and inorder traversal
1 parent 63e187b commit dfc9971

File tree

1 file changed

+25
-0
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
// 시간 : O(n^2)
3+
fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
4+
if (preorder.isEmpty() || inorder.isEmpty()) {
5+
return null
6+
}
7+
val value = preorder[0]
8+
var mid = inorder.indexOf(value)
9+
if (mid < 0) {
10+
mid = 0
11+
}
12+
val leftNode = buildTree(
13+
preorder.slice(1..preorder.lastIndex).toIntArray(),
14+
inorder.slice(0 until mid).toIntArray())
15+
val rightNode = buildTree(
16+
preorder.slice(2..preorder.lastIndex).toIntArray(),
17+
inorder.slice(mid + 1..inorder.lastIndex).toIntArray()
18+
)
19+
20+
return TreeNode(value).apply {
21+
left = leftNode
22+
right = rightNode
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)