constbinaryTree={val:1,left:{val:2,left:{val:4,},right:{val:5,}},right:{val:3,left:{val:6,left:{val:8}},right:{val:7,}}}顺序遍历constpreorder=(root)=>{if(!root)returnconststack=[root]while(stack.length){constn=stack.pop()console.log(n.val)if(n.right)stack.push(n.right)if(n.left)stack.push(n.left)}}preorder(binaryTree)中序遍历constinorder=(root)=>{if(!root)returnconststack=[]letp=rootwhile(stack.length||p){while(p){stack.push(p)p=p.left}constn=stack.pop()console.log(n.val)p=n.right}}inorder(binaryTree)后序遍历constpostorder=(root)=>{if(!root)returnconststack=[root]constres=[]while(stack.length){constn=stack.pop()res.push(n)if(n.left)stack.push(n.left)if(n.right)堆栈。push(n.right)}while(res.length){constn=res.pop()console.log(n.val)}}postorder(binaryTree)
