Problem:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
-Summary-
Used recursive DFS.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
self.res = 0
self.dfs(root, 0)
return self.res
def dfs(self, root, value):
if root:
self.dfs(root.left, value*10 + root.val)
self.dfs(root.right, value*10 + root.val)
if not root.left and not root.right:
self.res += value*10 + root.val
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > 2020 LeetCoding Challenge' 카테고리의 다른 글
LeetCode. Arranging Coins (0) | 2020.07.02 |
---|---|
LeetCode. Unique Paths (0) | 2020.06.30 |
LeetCode. Count Complete Tree Nodes (0) | 2020.06.24 |
LeetCode.Single Number II (0) | 2020.06.23 |
LeetCode.H-Index II (0) | 2020.06.19 |
댓글