240808
๋ฌธ์ : ๊ธธ ์ฐพ๊ธฐ ๊ฒ์ ๋์ด๋ : Lv.3
ํ์ด
function solution(nodeinfo) {
// ๋
ธ๋ ์ ๋ณด์ index๋ฅผ ์ถ๊ฐ (๋
ธ๋ ๋ฒํธ ์ ์ฅ)
nodeinfo = nodeinfo.map((node, index) => [...node, index + 1]);
// y ์ขํ ๊ธฐ์ค ๋ด๋ฆผ์ฐจ์, x ์ขํ ๊ธฐ์ค ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
nodeinfo.sort((a, b) => b[1] - a[1] || a[0] - b[0]);
// ์ด์ง ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ๋ ํจ์
function insertNode(parent, child) {
if (child[0] < parent[0]) {
if (parent.left === null) {
parent.left = child;
} else {
insertNode(parent.left, child);
}
} else {
if (parent.right === null) {
parent.right = child;
} else {
insertNode(parent.right, child);
}
}
}
// ํธ๋ฆฌ ๊ตฌ์กฐ ์์ฑ
let root = nodeinfo[0];
root.left = null;
root.right = null;
for (let i = 1; i < nodeinfo.length; i++) {
nodeinfo[i].left = null;
nodeinfo[i].right = null;
insertNode(root, nodeinfo[i]);
}
// ์ ์ ์ํ (Preorder)
let preorder = [];
function preorderTraversal(node) {
if (node) {
preorder.push(node[2]);
preorderTraversal(node.left);
preorderTraversal(node.right);
}
}
preorderTraversal(root);
// ํ์ ์ํ (Postorder)
let postorder = [];
function postorderTraversal(node) {
if (node) {
postorderTraversal(node.left);
postorderTraversal(node.right);
postorder.push(node[2]);
}
}
postorderTraversal(root);
return [preorder, postorder];
}
Last updated