function preOrder(node) {
if (!node) return
const stack = [node]
while (stack.length) {
const n = stack.pop()
console.log(n.value)
if (node.right) stack.push(n.right)
if (node.left) stack.push(n.left)
}
}
中序遍历
遍历顺序:左子树 ---> 根节点 ---> 右子树
对左子树中序遍历
访问根节点
对右子树中序遍历
输出:5 3 6 2 7 9 4 8 1 10
递归遍历
function inOrder(node) {
if (!node) return
preOrder(node.left)
console.log(node.value)
preOrder(node.right)
}
非递归遍历
function inOrder = (node) => {
if (!node) return
const stack = []
let p = node
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
const n = stack.pop()
console.log(n.value)
p = n.right
}
}
后序遍历
遍历顺序:左子树 ---> 右子树 ---> 根
对左子树后序遍历
对右子树后序遍历
访问根节点
输出: 5 6 3 9 7 8 4 2 10 1
递归遍历
function postOrder(node) {
if (!node) return
postOrder(node.left)
postOrder(node.right)
console.log(node.value)
}
非递归遍历
前序遍历根左右,将左右调换 push到新的栈 根右左,弹出即左右根
function postOrder = (node) => {
if (!node) return
const stack = [root]
const outputStack = []
while (stack.length) {
const n = stack.pop()
outputStack.push(n)
if (node.left) stack.push(n.left)
if (node.right) stack.push(n.right)
}
while (outputStack.length) {
const n = outputStack.pop()
console.log(n.value)
}
}
二叉树的定义
二叉树的作用
二叉树的遍历
前中后序 tree 结构
前序遍历
遍历顺序:根节点 ---> 左子树 ---> 右子树
非递归遍历 在栈中,打印出根节点值,push 进去右子树,左子树。先进后出弹出的左子树,右子树遍历。
中序遍历
遍历顺序:左子树 ---> 根节点 ---> 右子树
非递归遍历
后序遍历
遍历顺序:左子树 ---> 右子树 ---> 根
非递归遍历 前序遍历根左右,将左右调换 push到新的栈 根右左,弹出即左右根
深度广度 tree 结构
广度遍历
按层级一层层的遍历 输出:1 2 10 3 4 5 6 7 8 9
深度遍历
对每一个子节点深度遍历