二叉树遍历(先序、中序、后序、层次遍历)递归、循环实现
本文介绍二叉树遍历的以下四种
分别使用 循环遍历 递归遍历实现
-
前序遍历:根结点 — 左子树 — 右子树
-
中序遍历:左子树— 根结点 — 右子树
-
后序遍历:左子树 — 右子树 — 根结点
- 循环遍历的时候比先序和中序稍复杂
- 本文介绍两种供大家选择
-
层次遍历:按层次一层一层的遍历
先序遍历/先根遍历
- 递归实现
// 前序遍历
// 定义前序递归函数
private prevOrder(node: TreeNode<T> | null) {
if (!node) return
console.log(node.value)
this.prevOrder(node.left)
this.prevOrder(node.right)
}
//前序遍历函数
prevOrderTraversal() {
this.prevOrder(this.root!)
}
- 循环实现
prevOrderLoopTraversal() {
const stack: any[] = []
let root: TreeNode<T> | null = this.root
while (root || stack.length > 0) {
//这层循环主要是从一个节点遍历到最底层的左侧
while (root) {
console.log(root.value)
stack.push(root)
root = root.left
}
//如果到了最底层并且栈里还有未被遍历到的,弹出栈
if (stack.length > 0) {
root = stack.pop()
root = root!.right
}
}
}
中序遍历
- 递归实现
private inOrder(node: TreeNode<T> | null) {
if (!node) return
this.inOrder(node.left)
console.log(node.value)
this.inOrder(node.right)
}
inOrderTraversal() {
this.inOrder(this.root!)
}
- 循环实现
//和前序遍历的实现相似
//只需改变处理位置
inOrderLoopTraversal() {
const stack: any[] = []
let root: TreeNode<T> | null = this.root
while (root || stack.length > 0) {
//一直找到最底层的左子节点
while (root) {
stack.push(root)
root = root.left
}
//在每次到底弹出栈的时候打印这个值
if (stack.length > 0) {
root = stack.pop()
console.log(root!.value)
root = root!.right
}
}
}
后续遍历
- 递归实现
private postOrder(node: TreeNode<T> | null) {
if (!node) return
this.postOrder(node.left)
this.postOrder(node.right)
console.log(node.value)
}
postOrderTraversal() {
this.postOrder(this.root!)
}
- 循环实现
// 后序遍历---循环实现 --- 标记法
// 后续遍历的实现相对比前序和中序较为复杂
// 在打印的时候不知道是从左子节点回来的还是从右子节点回来的
// 需要添加标记来记录
postOrderLoopTraversal() {
interface obj {
node: TreeNode<T> | null
isLeft: boolean
}
const stack: obj[] = []
let root: obj = { node: this.root, isLeft: true }
while (root.node || stack.length > 0) {
while (root.node) {
stack.push({ node: root.node, isLeft: true })
root.node = root.node.left
}
if (!stack[stack.length - 1].isLeft && stack.length > 0) {
console.log(stack!.pop()?.node?.value)
}
if (stack.length > 0 && stack[stack.length - 1].isLeft) {
stack[stack.length - 1].isLeft = false
root.node = stack[stack.length - 1].node!.right
}
}
}
- 将先序遍历的循环稍微改动,输出的时候将结果反序
- 先序遍历(根-左-右)==> 稍微改动 - 逆先序遍历(根-右-左)
- 这个结果的反转就是后续遍历的结果
// 后序遍历---循环实现 --- 逆向前序遍历
postOrderLoopTraversal() {
const stack: any[] = []
let root: TreeNode<T> | null = this.root
let reverseOrder: T[] = []
while (root || stack.length > 0) {
while (root) {
reverseOrder.unshift(root.value)
stack.push(root)
root = root.right // 先序是先
}
if (stack.length > 0) {
root = stack.pop()
root = root?.left!
}
}
return reverseOrder.join('-')
}
层序遍历/顺序遍历
// 顺序遍历
// 运用队列思想来解决
// 按照顺序将节点一次进入队列,然后循环出队列
sequenTraversal() {
const queue: TreeNode<any>[] = []
queue.push(this.root!)
while (queue.length) {
const temp = queue.shift()
if (temp?.left) queue.push(temp.left)
if (temp?.right) queue.push(temp.right)
console.log(temp?.value)
}
}