Skip to content

Commit 762ca84

Browse files
committed
Adding sum-root-to-leaf-numbers (medium, ruby).
1 parent aee5a6d commit 762ca84

File tree

1 file changed

+34
-0
lines changed
  • medium/sum-root-to-leaf-numbers

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Definition for a binary tree node.
2+
class TreeNode
3+
attr_accessor :val, :left, :right
4+
def initialize(val)
5+
@val = val
6+
@left, @right = nil, nil
7+
end
8+
end
9+
10+
11+
def aux(root, accum)
12+
ret = 0
13+
ret += aux(root.left, root.val + (accum * 10)) if root.left
14+
ret += aux(root.right, root.val + (accum * 10)) if root.right
15+
16+
return ret if root.left or root.right
17+
18+
root.val + (accum * 10)
19+
end
20+
21+
# @param {TreeNode} root
22+
# @return {Integer}
23+
def sum_numbers(root)
24+
return 0 unless root
25+
aux(root, 0)
26+
end
27+
28+
# r = TreeNode.new(4)
29+
# r.left = TreeNode.new(9)
30+
# r.right = TreeNode.new(0)
31+
# r.left.left = TreeNode.new(5)
32+
# r.left.right = TreeNode.new(1)
33+
34+
# sum_numbers(r)

0 commit comments

Comments
 (0)