1. 程式人生 > >leetcood學習筆記-404-左葉子之和

leetcood學習筆記-404-左葉子之和

int tree bsp sel leave com alt color nod

題目描述:

技術分享圖片

方法一:遞歸

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if not root:
            return 0
        if root.left and root.left.left == None and root.left.right == None:
            return root.left.val+self.sumOfLeftLeaves(root.right)
        else:
            
return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)

方法二:

def sumOfLeftLeaves(self, root: TreeNode) -> int:

    # n == 0 表示為左節點
    # n == 1 表示為右節點
    def sum(root, n):
        if root == None:
            return 0
        if root.left == None and root.right == None and
n == 0: return root.val if root.left == None and root.right == None and n == 1: return 0 return sum(root.left, 0) + sum(root.right, 1) # 如果只有一個根節點 return 0 return sum(root, 1)

leetcood學習筆記-404-左葉子之和