mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
36 lines
858 B
JavaScript
36 lines
858 B
JavaScript
/**
|
|
* File: binary_tree.js
|
|
* Created Time: 2022-12-04
|
|
* Author: IsChristina (christinaxia77@foxmail.com)
|
|
*/
|
|
|
|
const { TreeNode } = require('../modules/TreeNode');
|
|
const { printTree } = require('../modules/PrintUtil');
|
|
|
|
/* Initialize the binary tree */
|
|
// Initialize the nodes
|
|
let n1 = new TreeNode(1),
|
|
n2 = new TreeNode(2),
|
|
n3 = new TreeNode(3),
|
|
n4 = new TreeNode(4),
|
|
n5 = new TreeNode(5);
|
|
// Set up references (pointers) between the nodes
|
|
n1.left = n2;
|
|
n1.right = n3;
|
|
n2.left = n4;
|
|
n2.right = n5;
|
|
console.log('\nInitialize the binary tree\n');
|
|
printTree(n1);
|
|
|
|
/* Insert and remove nodes */
|
|
const P = new TreeNode(0);
|
|
// Insert node P between n1 and n2 in n1 -> n2
|
|
n1.left = P;
|
|
P.left = n2;
|
|
console.log('\nAfter inserting node P:\n');
|
|
printTree(n1);
|
|
// Remove node P
|
|
n1.left = n2;
|
|
console.log('\nAfter removing node P:\n');
|
|
printTree(n1);
|