2022-12-04 12:26:09 +08:00
|
|
|
/**
|
|
|
|
* File: TreeNode.js
|
|
|
|
* Created Time: 2022-12-04
|
|
|
|
* Author: IsChristina (christinaxia77@foxmail.com)
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Definition for a binary tree node.
|
|
|
|
*/
|
2023-02-05 14:15:05 +08:00
|
|
|
class TreeNode {
|
2023-04-09 04:32:17 +08:00
|
|
|
val; // 节点值
|
|
|
|
left; // 左子节点指针
|
|
|
|
right; // 右子节点指针
|
|
|
|
height; //节点高度
|
2023-02-05 14:15:05 +08:00
|
|
|
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;
|
|
|
|
}
|
2022-12-04 12:26:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-02-05 14:15:05 +08:00
|
|
|
* Generate a binary tree given an array
|
|
|
|
* @param arr
|
|
|
|
* @return
|
|
|
|
*/
|
2023-08-13 19:30:50 +08:00
|
|
|
function arrToTree(arr, i = 0) {
|
|
|
|
if (i < 0 || i >= arr.length || arr[i] === null) {
|
|
|
|
return null;
|
2022-12-04 12:26:09 +08:00
|
|
|
}
|
2023-08-13 19:30:50 +08:00
|
|
|
let root = new TreeNode(arr[i]);
|
|
|
|
root.left = arrToTree(arr, 2 * i + 1);
|
|
|
|
root.right = arrToTree(arr, 2 * i + 2);
|
2022-12-04 12:26:09 +08:00
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
2023-02-05 14:15:05 +08:00
|
|
|
module.exports = {
|
2022-12-04 12:26:09 +08:00
|
|
|
TreeNode,
|
2023-04-17 21:58:11 +08:00
|
|
|
arrToTree,
|
2023-02-05 14:15:05 +08:00
|
|
|
};
|