前端树的相关算法
树的遍历要结合栈的思想 示例代码:
let tree = {
val: '1',
left: {
val: '2',
left: {
val: '4',
},
right: {
val: '3',
},
},
right: {
val: '5',
right: {
val: '6',
},
},
}
树的深度优先遍历
let dfs = (root) => {
if (!root) {
return
}
consloe.log(root.val)
if (root.left) dfs(root.left)
if (root.right) dfs(root.right)
}
树的广度优先遍历
let bfs = (root) => {
if (!root) {
return
}
let p = [root]
while (p.length) {
let n = p.shift()
if (n.left) p.push(n.left)
if (n.right) p.push(n.right)
}
}
树的先序遍历(根左右)
//递归解法
let preInorder = (root) => {
if (!root) {
return
}
console.log(root.val)
preInorder(root.left)
preInorder(root.right)
}
//栈解法
let preInorder = (root) => {
if (!root) {
return
}
let stack = [root]
while (stack.length) {
let n = stack.pop()
console.log(n.val)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
}
树的中序遍历(左根右)
//递归解法
let inInorder = (root) => {
if (!root) {
return
}
inInorder(root.left)
console.log(root.val)
inInorder(root.right)
}
//栈解法
let inInorder = (root) => {
if (!root) {
return
}
let stack = []
let p = root
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
const n = stack.pop()
console.log(n.val)
p = n.right
}
}
树的后序遍历(左右根)
//递归解法
let downInorder = (root) => {
if (!root) {
return
}
downInorder(root.left)
downInorder(root.right)
console.log(root.val)
}
//栈解法
let downInorder = (root) => {
if (!root) {
return
}
let stack = [root]
let outputStack = []
while (stack.length) {
const n = stack.pop()
outputStack.push(n)
if (n.left) stack.push(n.left)
if (n.right) stack.push(n.right)
}
while (outputStack.length) {
const n = outputStack.pop()
console.log(n.val)
}
}