二叉树结构constbinaryTree={val:1,left:{val:2,left:{val:4,},right:{val:5,}},right:{val:3,left:{val:6,left:{val:8}},right:{val:7,}}}1.前序遍历访问根节点对根节点的左子树进行前序遍历对根节点的右子树进行前序遍历constpreorder=(root)=>{if(!root)returnconsole.log(root.val)//访问根节点preorder(root.left)//遍历根节点的左子树preorder(root.right)//根节点右子树的前序遍历}preorder(binaryTree)2.根节点左子树的中序遍历。访问根节点,对根节点的右子树进行前序遍历。constinorder=(root)=>{if(!root)returninorder(root.left)//Inorder遍历左子树console.log(root.val)//访问根节点inorder(root.right)//inorder遍历右子树}inorder(binaryTree)3.后序遍历对根节点的左子树进行后序遍历对根节点的右子树进行后序遍历访问根节点constpostorder=(root)=>{if(!root)returnpostorder(root.left)//遍历左子树postorder(root.right)//遍历右子树console.log(root.val)//访问根节点}后序(二叉树)
