二叉树结构
const binaryTree = {
val: 1,
left: {
val: 2,
left: {
val: 4,
},
right: {
val: 5,
}
},
right: {
val: 3,
left: {
val: 6,
left: {
val: 8
}
},
right: {
val: 7,
}
}
}
1、先序遍历
- 访问根节点
- 对根节点的左子树进行先序遍历
- 对根节点的右子树进行先序遍历
const preorder = (root) => {
if (!root) return
console.log(root.val) // 访问根节点
preorder(root.left) // 先序遍历根节点的左子树
preorder(root.right) // 先序遍历根节点的右子树
}
preorder(binaryTree)
2、中序遍历
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历
const inorder = (root) => {
if (!root) return
inorder(root.left) // 中序遍历左子树
console.log(root.val) // 访问根节点
inorder(root.right) // 中序遍历右子树
}
inorder(binaryTree)
3、后序遍历
- 对根节点的左子树进行后序遍历
- 对根节点的右子树进行后序遍历
- 访问根节点
const postorder = (root) => {
if (!root) return
postorder(root.left) // 后序遍历左子树
postorder(root.right) // 后序遍历右子树
console.log(root.val) // 访问根节点
}
postorder(binaryTree)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。