背景:二叉树是一种数据结构,那么如果使用js遍历它呢
1、前序遍历,根--左--右
const frontTree = (tree) => {
let rs = [];
let trase = (vtree) => {
if(!vtree) {
return 'ooo';
}
rs.push(vtree.value);
rs.push(trase(vtree.left))
rs.push(trase(vtree.right))
}
trase(tree)
return rs;
}
2、中序遍历,左--根--右
const middleTree = (tree) => {
let rs = [];
let trase = (vtree) => {
if(!vtree) {
return 'ooo';
}
rs.push(trase(vtree.left))
rs.push(vtree.value);
rs.push(trase(vtree.right))
}
trase(tree)
return rs;
}
3、后序遍历,左--右--根
const endTree = (tree) => {
let rs = [];
let trase = (vtree) => {
if(!vtree) {
return 'ooo';
}
rs.push(trase(vtree.left))
rs.push(trase(vtree.right))
rs.push(vtree.value);
}
trase(tree)
return rs;
}
4、js的二叉数结构
const vTree = {
value: 1,
left: {
value: 2,
left: {
value: 3,
left: {value: 4},
right: {value: 5},
},
right: {
value: 6,
left: {value: 7},
right: {value: 8},
}
},
right: {
value: 9,
left: {value: 10},
right: {value: 11}
}
}
执行
console.log(frontTree(vTree));
console.log(middleTree(vTree));
console.log(endTree(vTree));
结果是:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。