題目描述
給你一棵二叉樹,請你返回滿足以下條件的所有節點的值之和:
該節點的祖父節點的值爲偶數。(一個節點的祖父節點是指該節點的父節點的父節點。)
如果不存在祖父節點值爲偶數的節點,那麼返回 0 。
算法思路
深度優先搜索
方法內的變量+輔助函數
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
self.res=0
def helper(root,g='',p=''):
if not root:return 0
if g and g.val%2==0:
self.res+=root.val
helper(root.left,p,root)
helper(root.right,p,root)
return self.res
return helper(root)
執行用時 :112 ms, 在所有 Python3 提交中擊敗了71.46%的用戶
內存消耗 :17.2 MB, 在所有 Python3 提交中擊敗了100.00%的用戶
做了一點優化,刪掉了輔助函數以及獨立的變量self.res
class Solution:
def sumEvenGrandparent(self, root,res=0,g='',p='') -> int:
if not root:return res
if g and g.val%2==0:
res+=root.val
res=self.sumEvenGrandparent(root.left,res,p,root)
res=self.sumEvenGrandparent(root.right,res,p,root)
return res
執行用時 :116 ms, 在所有 Python3 提交中擊敗了59.70%的用戶
內存消耗 :17.2 MB, 在所有 Python3 提交中擊敗了100.00%的用戶