Skip to content

Commit ea2fb75

Browse files
committed
construct-binary-tree-from-preorder-and-inorder-traversal
1 parent 7977d22 commit ea2fb75

File tree

1 file changed

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

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
3+
* Definition for a binary tree node.
4+
* function TreeNode(val, left, right) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.left = (left===undefined ? null : left)
7+
* this.right = (right===undefined ? null : right)
8+
* }
9+
*/
10+
/**
11+
* @param {number[]} preorder
12+
* @param {number[]} inorder
13+
* @return {TreeNode}
14+
*/
15+
var buildTree = function (preorder, inorder) {
16+
// ํ•ด์‹œ๋งต์„ ๋งŒ๋“ค์–ด ์ค‘์œ„ ์ˆœํšŒ์˜ ๊ฐ’ -> ์ธ๋ฑ์Šค๋ฅผ ๋น ๋ฅด๊ฒŒ ์ฐพ์„ ์ˆ˜ ์žˆ๋„๋ก ํ•จ
17+
const inorderMap = new Map();
18+
inorder.forEach((val, idx) => {
19+
inorderMap.set(val, idx);
20+
});
21+
22+
// preorder๋ฅผ ์ˆœํšŒํ•  ์ธ๋ฑ์Šค
23+
let preorderIndex = 0;
24+
25+
/**
26+
* ์žฌ๊ท€ ํ•จ์ˆ˜: ํ˜„์žฌ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ์ค‘์œ„ ์ˆœํšŒ ๊ตฌ๊ฐ„(start ~ end)์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“ ๋‹ค.
27+
*/
28+
function arrayToTree(left, right) {
29+
// ์ข…๋ฃŒ ์กฐ๊ฑด: ๊ตฌ๊ฐ„์ด ์ž˜๋ชป๋˜๋ฉด ๋…ธ๋“œ๊ฐ€ ์—†์Œ
30+
if (left > right) return null;
31+
32+
// preorder์—์„œ ํ˜„์žฌ ๋ฃจํŠธ ๊ฐ’ ์„ ํƒ
33+
const rootVal = preorder[preorderIndex];
34+
preorderIndex++; // ๋‹ค์Œ ํ˜ธ์ถœ์„ ์œ„ํ•ด ์ธ๋ฑ์Šค ์ฆ๊ฐ€
35+
36+
// ํ˜„์žฌ ๋…ธ๋“œ ์ƒ์„ฑ
37+
const root = new TreeNode(rootVal);
38+
39+
// ๋ฃจํŠธ ๊ฐ’์˜ ์ค‘์œ„ ์ˆœํšŒ ์ธ๋ฑ์Šค ์ฐพ๊ธฐ
40+
const index = inorderMap.get(rootVal);
41+
42+
// ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ์ƒ์„ฑ
43+
root.left = arrayToTree(left, index - 1);
44+
root.right = arrayToTree(index + 1, right);
45+
46+
return root;
47+
}
48+
49+
// ์ „์ฒด inorder ๋ฒ”์œ„๋กœ ์‹œ์ž‘
50+
return arrayToTree(0, inorder.length - 1);
51+
};

0 commit comments

Comments
ย (0)