zoukankan      html  css  js  c++  java
  • 左叶子之和

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

    示例:

        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
  • 相关阅读:
    B2. Cat Party (Hard Edition)
    Dubbo集群容错
    Dubbo负载均衡
    Dubbo多协议支持
    Dubbo服务分组
    Dubbo多版本控制
    Dubbo管控平台
    Dubbo应用到web工程
    Dubbo使用Zookeeper注册中心
    Dubbo直连方式
  • 原文地址:https://www.cnblogs.com/yejiang/p/10301016.html
Copyright © 2011-2022 走看看