JS ES6 stack solution


  • 0
    Y
    function peek(stack) {
      return stack[stack.length - 1]
    }
    
    function postorderTraversal(treeNode) {
      const traversal = []
      const stack = []
      let node = treeNode
      while (node || stack.length)  {
        if (node) {
          stack.push(node)
          node = node.left
        } else {
          const {left, right, val} = peek(stack)
          if (right && (peek(traversal) !== right)) {
            node = right
          } else {
            traversal.push(stack.pop())
          }
        }
      }
      return traversal.map(({val}) => val)
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.