Files
hello-algo/en/codes/javascript/modules/TreeNode.js
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

36 lines
904 B
JavaScript

/**
* File: TreeNode.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* Binary tree node */
class TreeNode {
val; // Node value
left; // Pointer to the left child
right; // Pointer to the right child
height; //Node 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;
}
}
/* Deserialize an array into a binary tree */
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,
};