如何解决在 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: ");
上面的代码没有按预期工作。我认为这是由于异步和递归造成的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。