放一个二叉树的例子
<html>
<body>
<script>
var tree = {
id: 0,
name: "root",
left: {
id: 1,
name: "Simon",
left: {
id: 3,
name: "Carl",
left: {
id: 7,
name: "Lee",
left: {
id: 11,
name: "Fate",
},
},
right: {
id: 8,
name: "Annie",
left: {
id: 12,
name: "Saber",
},
},
},
right: {
id: 4,
name: "Tony",
left: {
id: 9,
name: "Candy",
},
},
},
right: {
id: 2,
name: "right",
left: {
id: 5,
name: "Carl",
},
right: {
id: 6,
name: "Carl",
right: {
id: 10,
name: "Kai",
},
},
},
};
// 假设id和name均不会重复,根据输入name找到对应的id
function findIdByName(name) {
var id;
function node(tree) {
if (tree) {
if (tree.name == name) {
id = tree.id;
}
node(tree.left);
node(tree.right);
}
}
node(tree);
return id;
}
console.log(findIdByName("Annie"));
// 假设id和name均不会重复,根据输入id找到对应的name
function findNameById(id) {
var name;
function node(tree) {
if (tree) {
if (tree.id == id) {
name = tree.name;
}
node(tree.left);
node(tree.right);
}
}
node(tree);
return name;
}
console.log(findNameById("8"));
// 把这个对象中所有的名字以“前序遍历”的方式全部输出到console中
var dlr = [];
function getListWithDLR() {
function node(tree) {
if (tree) {
dlr.push(tree.name);
node(tree.left);
node(tree.right);
}
}
node(tree);
console.log(dlr);
}
getListWithDLR();
// 把这个对象中所有的名字以“中序遍历”的方式全部输出到console中
var ldr = [];
function getListWithLDR() {
function node(tree) {
if (tree) {
node(tree.left);
ldr.push(tree.name);
node(tree.right);
}
}
node(tree);
console.log(ldr);
}
getListWithLDR();
// 把这个对象中所有的名字以“后序遍历”的方式全部输出到console中
var lrd = [];
function getListWithLRD() {
function node(tree) {
if (tree) {
node(tree.left);
node(tree.right);
lrd.push(tree.name);
}
}
node(tree);
console.log(lrd);
}
getListWithLRD();
</script>
</body>
</html>