二叉树结构

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,
        }
    }
}

image.png
1、先序遍历

  1. 访问节点
  2. 对根节点的子树进行先序遍历
  3. 对根节点的子树进行先序遍历
const preorder = (root) => {
    if (!root) return
    console.log(root.val) // 访问根节点
    preorder(root.left) // 先序遍历根节点的左子树
    preorder(root.right) // 先序遍历根节点的右子树
}

preorder(binaryTree)

image.png

2、中序遍历

  1. 对根节点的子树进行中序遍历
  2. 访问节点
  3. 对根节点的子树进行中序遍历
const inorder = (root) => {
    if (!root) return
    inorder(root.left) // 中序遍历左子树
    console.log(root.val) // 访问根节点
    inorder(root.right) // 中序遍历右子树
}

inorder(binaryTree)

image.png

3、后序遍历

  1. 对根节点的子树进行后序遍历
  2. 对根节点的子树进行后序遍历
  3. 访问节点
const postorder = (root) => {
    if (!root) return
    postorder(root.left) // 后序遍历左子树
    postorder(root.right) // 后序遍历右子树
    console.log(root.val) // 访问根节点
}

postorder(binaryTree)

image.png


anchen
21 声望1 粉丝