javascript - 在 node.js 中创建二叉树并从控制台获取输入
问题描述
如何通过逐个节点从控制台获取输入并形成树来在 node.js 中创建二叉树?
想创造这样的东西:
4
/ \
6 5
/ \
8 2
Enter Root Node: 4 Left Child of 4: 6 Left Child of 6: 8 Left Child of 8: * Right Child of 6: 2 Right Child of 4: 5 Left Child of 5: * Right Child of 5: *
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function binaryTree() {
let root = null;
function Node(element) {
this.element = element;
this.left = null;
this.right = null;
}
function create(question) {
rl.question(question, (answer) => {
if(answer == "*") {
return "*";
}
if(answer.includes("exit")) {
answer = answer.split(" ")[0];
rl.close();
if(answer == "*") {
return "*";
}
}
let newNode = new Node(answer);
if(root === null) root = newNode;
newNode.left = create("Left Child of " + answer + ": ");
newNode.right = create("Right Child of " + answer + ": ");
return newNode;
});
}
function preOrder(head) {
console.log("head: " + head);
if( head == "*" || head == null ) {
return;
}
console.log(head.element);
preOrder(head.left);
preOrder(head.right);
}
function getRoot() {
return root;
}
return { create, preOrder, getRoot };
}
let bTree = binaryTree();
let bTree_root = bTree.getRoot();
bTree.create("Root Value: ");
上面的代码没有按预期工作。我认为这是由于异步和递归。
解决方案
推荐阅读
- c# - 调试 .net Core IModelBinder 有 Visual Studio 跳线
- linux - 如何从 Linux 上的 Windows 注册表中检索区域设置?
- java - Intellij 打不开我的 JDK 所在的文件夹
- php - PHPUnit 错误“无法打开流:没有这样的文件或目录”
- android - com.android.chrome 导致的崩溃
- laravel - 如何将路由变量值传递给模型类方法
- c++ - 与 C++ 中的循环和变异向量混淆
- javascript - 浏览器中 Javascript 源代码中的“w()”、“n()”
- python - Pandas 基于模式长度的阈值数据序列
- r - 嵌套 rollmean - 如何避免来自每个 DF 边缘的 NA