leetcode with python:404. Sum of Left Leaves

题目:

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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章