树的遍历
let tree = {
val: 1,
children: [
{
val: 2,
children: [
{val: 4, children:[]},
{val: 5, children: []}
]
},
{
val: 3,
children: [
{val: 6, children:[]},
{val: 7, children:[]},
]
}
]
}
const fun = (root) => {
console.log(root.val)
root.forEach(fun)
}
1、新建队列,根节点入队
2、把对头出队
3、把对头的children挨个入队
4、重复2、3步,直到队列为空为止
const fun = (root) => {
let arr = [root]
while(arr.length){
const o = arr.shift()
o.children.forEach(item => {
console.log(o.val)
arr.push(item)
})
}
}
二叉树的遍历
let binaryTree = {
val: 1,
left: {
val: 2,
left: {val: 4, left: null, right: null},
right: {val: 5, left: null, right: null}
},
right: {
val: 3,
left: {val: 6, left: null, right: null},
right: {val: 7, left: null, right: null}
}
}
// 递归方式实现
let arr = []
const fun = (node) => {
if(node){
arr.push(node.val)
fun(node.left)
fun(node.right)
}
}
fun(binaryTree)
console.log(arr)
//栈的方式实现
if(!root){
return []
}
let arr = []
let stack = [root]
while(stack.length){
let o = stack.pop()
arr.push(o.val)
o.right && arr.push(o.right)
o.left && arr.push(o.left)
}
console.log(arr)
- 3、中序遍历(左根右4、2、5、1、6、3、7)
- 4、后序遍历