LeetCode 145 Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

# Definition for a binary tree node
# class TreeNode
#     attr_accessor :val, :left, :right
#     def initialize(val)
#         @val = val
#         @left, @right = nil, nil
#     end
# end

# @param {TreeNode} root
# @return {Integer[]}
def postorder_traversal(root)
    stack = [[false, root]]
    ans = []
    while not stack.empty?
        f, n = stack.pop()
        if n
            if not f
                stack << [true, n] << [false, n.right] << [false, n.left]
            else
                ans << n.val
            end
        end
    end
    ans
end


你可能感兴趣的:(LeetCode)