You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
882 B
36 lines
882 B
8 months ago
|
/**
|
||
|
* File: TreeNode.js
|
||
|
* Created Time: 2022-12-04
|
||
|
* Author: IsChristina (christinaxia77@foxmail.com)
|
||
|
*/
|
||
|
|
||
|
/* 二元樹節點 */
|
||
|
class TreeNode {
|
||
|
val; // 節點值
|
||
|
left; // 左子節點指標
|
||
|
right; // 右子節點指標
|
||
|
height; //節點高度
|
||
|
constructor(val, left, right, height) {
|
||
|
this.val = val === undefined ? 0 : val;
|
||
|
this.left = left === undefined ? null : left;
|
||
|
this.right = right === undefined ? null : right;
|
||
|
this.height = height === undefined ? 0 : height;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/* 將陣列反序列化為二元樹 */
|
||
|
function arrToTree(arr, i = 0) {
|
||
|
if (i < 0 || i >= arr.length || arr[i] === null) {
|
||
|
return null;
|
||
|
}
|
||
|
let root = new TreeNode(arr[i]);
|
||
|
root.left = arrToTree(arr, 2 * i + 1);
|
||
|
root.right = arrToTree(arr, 2 * i + 2);
|
||
|
return root;
|
||
|
}
|
||
|
|
||
|
module.exports = {
|
||
|
TreeNode,
|
||
|
arrToTree,
|
||
|
};
|