class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.left = b
a.right = c
# 這道題用遞回來做,很容易就做出來的
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
# 定義一個變數,用來存盤最后的和
self.sum_num = 0
# 判斷二叉樹是否為空,如果為空,直接回傳0
if not root : return 0
def dfs(root,num):
# 判斷當前節點是否為空
if not root:return
# 根據題意進行相加,
num = num * 10 + root.val
# 注意這里,不能讓他走到節點為空的那一層,那樣的話就多算一遍,
if not root.left and not root.right:
self.sum_num = self.sum_num + num
return
# 然后分別遞回左右子樹
dfs(root.left,num)
dfs(root.right,num)
dfs(root,0)
# 最后回傳計算出來的結果
return self.sum_num
A = Solution()
print(A.sumNumbers(a))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/73420.html
標籤:Python
上一篇:python練習004
下一篇:130被圍繞的區域
