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.
|
|
|
|
*/
|
|
|
|
function TreeNode(val, left, right) {
|
2022-12-13 21:44:14 +08:00
|
|
|
this.val = (val === undefined ? 0 : val); // 结点值
|
|
|
|
this.left = (left === undefined ? null : left); // 左子结点指针
|
|
|
|
this.right = (right === undefined ? null : right); // 右子结点指针
|
2022-12-04 12:26:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-01-08 19:03:22 +08:00
|
|
|
* Generate a binary tree given an array
|
2022-12-04 12:26:09 +08:00
|
|
|
* @param arr
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
function arrToTree(arr) {
|
|
|
|
if (arr.length === 0)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
let root = new TreeNode(arr[0]);
|
|
|
|
let queue = [root]
|
2023-01-08 19:03:22 +08:00
|
|
|
let i = 0;
|
|
|
|
while (queue.length) {
|
2022-12-04 12:26:09 +08:00
|
|
|
let node = queue.shift();
|
2023-01-08 19:03:22 +08:00
|
|
|
if (++i >= arr.length) break;
|
|
|
|
if (arr[i] !== null) {
|
2022-12-04 12:26:09 +08:00
|
|
|
node.left = new TreeNode(arr[i]);
|
|
|
|
queue.push(node.left);
|
|
|
|
}
|
2023-01-08 19:03:22 +08:00
|
|
|
if (++i >= arr.length) break;
|
|
|
|
if (arr[i] !== null) {
|
2022-12-04 12:26:09 +08:00
|
|
|
node.right = new TreeNode(arr[i]);
|
|
|
|
queue.push(node.right);
|
|
|
|
}
|
|
|
|
}
|
2023-01-08 19:03:22 +08:00
|
|
|
|
2022-12-04 12:26:09 +08:00
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
TreeNode,
|
|
|
|
arrToTree,
|
|
|
|
}
|