左叶子之和

计算给定二叉树的所有左叶子之和。

示例:

    3
   / 
  9  20
    /  
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

解法:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue
class Solution:
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        q = queue.Queue()
        q.put(root)
     #用来装树所有左孩子的列表 List
= list()
     #通过层次遍历将所有左孩子放入List
while not q.empty(): width = q.qsize() theFirst = True for i in range(width): p = q.get() if p.left != None: q.put(p.left) List.append(p.left) if p.right != None: q.put(p.right) total = 0
     #再遍历List,将其中是叶子节点的值全加起来
for x in List: if x.left==None and x.right==None: total += x.val return total
原文地址:https://www.cnblogs.com/yejiang/p/10301016.html