版权声明:原创文章,如想转载,请注明原文网址,注明出处;否则,禁止转载;谢谢配合! https://blog.csdn.net/c_kite/article/details/81510787
序言
最近看了些面试题, 发现大多数都会问一个问题就是JavaScript生成二叉树, 本来想偷懒百度看看算了, 可是发现好多网站博客的代码都是一样的, 并且生成的还是平衡二叉树………. 如果我不输入数字你给我生成一个试试. so, 看起来只能自己搞一下了.
我之前写过一篇基于C++的二叉树创建以及遍历方法, 本片博客算法就是基于之前的C++语言的改版. 附上链接: https://blog.csdn.net/c_kite/article/details/52833961
生成二叉树的格式:
代码
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function MyNode(value = '', left = null, right = null) {
this.root = value;
this.left = left;
this.right = right;
}
let i = 0
function createTree(data, node = null) {
if (i >= data.length) return null
if (data[i] === '#') {
i++;
return null;
}
// 由于js没有指针和引用, 没法在递归的函数里设置上一步递归的左右子树, 只能先创建一个对象把地址先分配好. 因此这样创建完会有一个弊端, 二叉树的叶子节点上多了这些的空节点. 如果你有好的建议可以留言, 或者私信我.
let left = new MyNode(null, null, null);
let right = new MyNode(null, null, null);
if (node === null) {
node = new MyNode(data[i], left, right);
} else {
node.root = data[i];
node.left = left;
node.right = right;
}
i++
createTree(data, node.left);
createTree(data, node.right);
return node
}
let data = [];
// rl.question('请输入想要创建的二叉树', (answer) => {
// data = answer.split('');
// console.log(createTree(data))
// rl.close();
// });
// 我嫌每次输入麻烦就写死了
data = 'GDA##FE###MH##Z###'.split('');
let result = createTree(data);
show_DLR(result)
function show_DLR(result) {
let stack = [], queue = [];
let now = result;
while(now.root !== null || queue.length !== 0) {
if(now.root !== null) { // 遍历左子树
stack.push(now); // 分别将二叉树的结点压入栈和队列中
queue.push(now);
now = now.left;
}
else {
console.log(queue.shift().root)// 注意此时弹出的为队列中的第一个元素
now = stack.pop().right;
}
}
}
// 偷懒了...... 其余的几种的遍历请参考序言中提到的博客链接
// https://blog.csdn.net/c_kite/article/details/52833961
// 我的这篇博客是C++写的, 但是逻辑你可以copy过来