postorder traversal Algorithm
In computer science, tree traversal (also known as tree search and walking the tree) is a form of graph traversal and refers to the procedure of visiting (checking and/or update) each node in a tree data structure, precisely once. The following algorithms are described for a binary tree, but they may be generalized to other trees as well.
# 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)
ans = []
def traverse(node, ans)
if node != nil
traverse(node.left, ans)
traverse(node.right, ans)
ans.push(node.val)
end
end
traverse(root, ans)
return ans
end