本篇内容介绍了“layer深度优先、广度优先创建n叉树的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
1
function makeTree(layer) {
const root = {};
makeNode(root, layer);
return root;
}
function makeNode(node, layer, keys = ['left', 'right']) {
if (!--layer) {
keys.forEach((key) => {
node[key] = null;
})
return;
}
keys.forEach((key) => {
node[key] = {};
});
keys.forEach((key) => {
makeNode(node[key], layer);
});
}2
function makeTree(layer, keys = ['left', 'right']) {
if (!layer) {
return null;
}
layer--;
const node = {};
keys.forEach((key) => {
node[key] = makeTree(layer);
});
return node;
}3
function makeBinaryTree(layer = 4) {
function Node(opts) {
return opts;
}
const root = {value: 0, layer: 0};
let queue = [root];
let current;
while(current = queue.shift()) {
if (current.layer == layer) {
return root;
}
current.left = new Node({value: 0, layer: current.layer + 1});
current.right = new Node({value: 1, layer: current.layer + 1});
queue.push(current.left);
queue.push(current.right);
}
}“layer深度优先、广度优先创建n叉树的方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/223320.html