js递归,二叉树的操作
//递归算法n次幂
function foo(n) {
if (n == 1) {
return 1;
} else {
return n * foo(n - 1);
}
}
//console.log(foo(3));var nodes = {
name: ‘root‘, childs: [
{ name: ‘a1‘ },
{ name: ‘a2‘ },
{ name: ‘a3‘ },
{ name: ‘b1‘ },
{ name: ‘b2‘ },
{
name: ‘b3‘, childs: [
{ name: ‘bb1‘ },
{ name: ‘bb2‘ },
{ name: ‘bb3‘ }
]
}
]
}
//递归树形节点
function output(node) {
console.log(node.name);
if (node.childs && node.childs.length > 0) {
node.childs.forEach(function (el, i) {
//递归
output(el);
});
}
}
//output(nodes);
//二叉树
var tree = {
value: 100,
left: {
value: 80,
left: {
value: 70
},
right: {
value: 90
}
},
right: {
value: 200,
left: {
value: 180
}, right: {
value: 220
}
}
}
//二叉树遍历(递归算法,容易导致运行栈溢出)
function printTree(tree) {
console.log(tree.value)
if (tree.left) {
printTree(tree.left);
}
if (tree.right) {
printTree(tree.right);
}
}
//printTree(tree);
//二叉树的查找
var count = 0;
function findInTree(tree, v) {
count++;
if (v > tree.value && tree.right) {
findInTree(tree.right, v)
} else if (v < tree.value && tree.left) {
findInTree(tree.left, v)
} else if(v==tree.value){
console.log(‘存在该节点,节点值为:‘,tree.value);
return 0;
}else{
console.log(‘不存在该节点!‘);
return -1;
}
}
//findInTree(tree,70);
//console.log(count);
//二叉树的插入
function insertTree(tree, v) {
if (v > tree.value) {
if (tree.right) {//如果有子节点继续遍历
insertTree(tree.right, v);
} else {
tree.right = { value: v };
}
} else if (v < tree.value) {
if (tree.left) {//如果有子节点继续遍历
insertTree(tree.left, v);
} else {
tree.left = { value: v };
} } else {
console.log(‘树中已存在该节点‘);
}
}
//insertTree(tree,505);
//console.log(tree);
//二叉树的生成(以一个数组中的任意元素为树的根节点)
var data = [12, 23, 45, 123, 5, 89, 42, 32, 69, 11, 87, 25];
//生成一个随机的索引
var rindex = Math.floor(Math.random() * data.length);
//随机获取data中的一个元素作为二叉树的根元素
var prodTree = { value: data[rindex] };
//使用根元素和数组为参数 创建索引
function createTree(node, data) {
data.forEach(function (v) {
//将数组的每个元素插入二叉树中
insertTree(node,v);
});
}
createTree(prodTree,data);
//遍历生成的二叉树每个节点的值
printTree(prodTree);
原文地址:https://www.cnblogs.com/lovellll/p/10208214.html
时间: 2024-10-16 06:31:00