TheAlgorithms-Ruby/data_structures/binary_trees/preorder_traversal.rb
2020-05-14 11:05:14 +09:00

23 lines
No EOL
451 B
Ruby

# 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 preorder_traversal(root)
ans = []
def traverse(node, ans)
if node != nil
ans.push(node.val)
traverse(node.left, ans)
traverse(node.right, ans)
end
end
traverse(root, ans)
return ans
end