# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
integer,string, tuple are immutable, when passed in function they can not be modified in place
immutable objects:
Numeric types: int, float, complex
string
tuple
frozen set
bytes
mutable:
list
dict
set
byte array
"""
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root : return 0
res=[]
curr=[]
def dfs(node,curr,res):
curr.append(str(node.val))
if not node.left and not node.right:
#print curr
res.append(int(''.join(curr)))
else:
if node.left:
dfs(node.left,curr,res)
curr.pop()
if node.right:
dfs(node.right,curr,res)
curr.pop()
dfs(root,curr,res)
#print res
return sum(res)
129. Sum Root to Leaf Numbers
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- Given a binary tree containing digits from 0-9 only, each...
- 題目129. Sum Root to Leaf Numbers Given a binary tree conta...
- Given a binary tree containing digits from 0-9 only, each...
- 129. Sum Root to Leaf Numbers 題目:https://leetcode.com/pro...
- 方法1:最容易想到的就是遞歸方法,保持一個response,每到一個葉節點就把結果與res相加 方法2:還可以用迭...