数据:
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": "Carl2",
},
"right": {
"id": 6,
"name": "Carl3",
"right": {
"id": 10,
"name": "Kai"
}
}
}
}
先序遍历输出所有name值:
var backsD = [];
function getListWithDLR(node) {
if (node) {
backsD.push(node.name);
getListWithDLR(node.left);
getListWithDLR(node.right);
}
}
getListWithDLR(tree);
console.log('backsD:'+backsD.join());
输出结果图解:
先序遍历.png
中序遍历输出所有name值:
var backsL = [];
function getListWithLDR(node) {
if (node) {
getListWithLDR(node.left);
backsL.push(node.name);
getListWithLDR(node.right);
}
}
getListWithLDR(tree);
console.log('backsL:'+backsL.join());
输出结果图解:
中序遍历.png后序遍历打印所有name值:
// 把这个对象中所有的名字以“后序遍历”的方式全部输出到console中
var backsR = [];
function getListWithLRD(node) {
if (node) {
getListWithLRD(node.left);
getListWithLRD(node.right);
backsR.push(node.name);
}
}
getListWithLRD(tree);
console.log('backsR:'+backsR.join());
输出顺序图解:
后序遍历.png
网友评论