Python實(shí)現(xiàn)"左葉子之和"的兩種方法

題目

給定一顆二叉樹,返回它所有左葉子節(jié)點(diǎn)之和

舉例

    3
   / \
  9  20
    /  \
   15   7
return 24

遞歸方法

def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if not root.left and not root.right:   #當(dāng)前節(jié)點(diǎn)不存在左右子樹
            return 0
        if not root.left and root.right:       #當(dāng)前節(jié)點(diǎn)只有右子樹
            return self.sumOfLeftLeaves(root.right)
        if root.left and not root.right:     #當(dāng)前節(jié)點(diǎn)只有左子樹
            if not root.left.left and not root.left.right:   #當(dāng)前節(jié)點(diǎn)的左節(jié)點(diǎn)不存在左右子樹
                return root.left.val
            else:
                return self.sumOfLeftLeaves(root.left)
        sum = 0
        if root.left and root.right:        #當(dāng)前節(jié)點(diǎn)既有左子樹又有右子樹
            if not root.left.left and not root.left.right:         #當(dāng)前節(jié)點(diǎn)的左子樹沒有左右節(jié)點(diǎn)
                sum += root.left.val
            else:
                sum += self.sumOfLeftLeaves(root.left)
            sum += self.sumOfLeftLeaves(root.right)
        return sum

簡(jiǎn)化遞歸寫法(參考他人)

def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        sum = 0
        if root.left and not root.left.left and not root.left.right:
            sum += root.left.val
        sum += self.sumOfLeftLeaves(root.left)
        sum += self.sumOfLeftLeaves(root.right)
        return sum
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容