生活随笔
收集整理的這篇文章主要介紹了
404. 左叶子之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
404. 左葉子之和
找到左葉子
方法一:遞歸
判斷根節點是否有左子樹,用sum_left記錄遞歸左子樹與右子樹,找出其中的葉子節點
class Solution:def sumOfLeftLeaves(self
, root
: TreeNode
) -> int:sum_left
= 0if not root
:return 0if root
.left
and not (root
.left
.left
or root
.left
.right
):sum_left
= root
.left
.val
return sum_left
+ self
.sumOfLeftLeaves
(root
.left
) + self
.sumOfLeftLeaves
(root
.right
)
方法二 棧
求出所有葉子點的和減去右葉子節點的和
在通過棧遍歷的基礎上修改的
class TreeNode:def __init__(self
, val
=0, left
=None, right
=None):self
.val
= valself
.left
= leftself
.right
= right
class Solution:def sumOfLeftLeaves(self
, root
: TreeNode
) -> int:if not root
:return 0sum_left
= 0stack
= []last_visit
= root
while root
or stack
:while root
:stack
.append
(root
)root
= root
.leftroot
= stack
[-1]if root
.right
!= last_visit
:root
= root
.right
if root
and not (root
.left
or root
.right
):sum_left
-= root
.val
if not root
:last_visit
= Noneelse:temp
= stack
.pop
()if not (temp
.left
or temp
.right
):sum_left
+= root
.vallast_visit
= temproot
= Nonereturn sum_left
總結
以上是生活随笔為你收集整理的404. 左叶子之和的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。