二叉树构造

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、先序遍历

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

2、中序遍历

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

3、后序遍历

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