Skip to content
On this page

145. Binary Tree Postorder Traversal

https://leetcode.com/problems/binary-tree-postorder-traversal/

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
  if (!root) {
    return []
  }

  var result = []
  result = result.concat(postorderTraversal(root.left))
  result = result.concat(postorderTraversal(root.right))
  result.push(root.val)
  return result
}
js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
  if (!root) {
    return []
  }

  var result = []
  var stack = [root]
  var current = null

  while (stack.length) {
    let top = stack[stack.length - 1]
    let invalidTop = !top.left && !top.right
    let isTopChild = current && (current === top.left || current === top.right)

    if (invalidTop || isTopChild) {
      stack.pop()
      result.push(top.val)
      current = top
    } else {
      if (top.right) {
        stack.push(top.right)
      }
      if (top.left) {
        stack.push(top.left)
      }
    }
  }

  return result
}
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        result = []
        result.extend(self.postorderTraversal(root.left))
        result.extend(self.postorderTraversal(root.right))
        result.append(root.val)
        return result
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        result = []
        stack = [root]
        current = None
        while stack:
            top = stack[-1]
            invalidTop = not top.left and not top.right
            isTopChild = current and (
                current is top.left or current is top.right)
            if invalidTop or isTopChild:
                stack.pop()
                result.append(top.val)
                current = top
            else:
                if top.right:
                    stack.append(top.right)
                if top.left:
                    stack.append(top.left)
        return result