题目:
Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
给定一binary tree的root,回传其所有左叶值的和
这题自己写一个判断Node是不是leaf的函式会方便不少
# 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 = rightclass Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: def isleaf(root): if root and root.left==None and root.right==None: return True else: return False ans=[0] def x(root): if not root: return if isleaf(root.left): ans[0]=ans[0]+root.left.val else: x(root.left) if not isleaf(root.right): x(root.right) x(root) return ans[0]
先自製一个判断Node是不是leaf的函式
接着开始递迴,若一开始root是None直接return
利用事先写好的函式判断root.left和root.right是不是leaf
若root.left是leaf则将其值加到ans[0]
同时因为它不会有左leaf,所以不用往下探索了
同理,若root.right是leaf,也不用往下探索
最后回传ans[0]
最后执行时间28ms(faster than 98.38%)
那我们下题见