leetcode 404. Sum of Left Leaves
来源:互联网 发布:淘宝面膜排行榜 编辑:程序博客网 时间:2024/06/05 21:13
Python leetcode
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
主要是求一个树的左叶节点的和。
#coding=utf-8
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#求所有左叶节点的和
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if root.left and not root.left.left and not root.left.right:
return root.left.val +self.sumOfLeftLeaves(root.right)
return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)
# 求右节点的和
def sumOfRightLeaves(self,root):
if not root:return 0
if root.right and not root.right.left and not root.right.right:
return root.right.val + self.sumOfLeftLeaves(root.left)
return self.sumOfRightLeaves(root.left)+self.sumOfRightLeaves(root.right)
tree=TreeNode(10)
tree.left=TreeNode(9);tree.right=TreeNode(20)
tree.right.left=TreeNode(15);tree.right.right=TreeNode(7)
s=Solution()
print s.sumOfLeftLeaves(tree)
print s.sumOfRightLeaves(tree)
0 0
- LeetCode笔记:404. Sum of Left Leaves
- 【leetcode】404. Sum of Left Leaves【E】
- LeetCode—404. Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves
- Leetcode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- 404. Sum of Left Leaves - leetcode
- [LeetCode]--404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- [leetcode]404. Sum of Left Leaves
- LeetCode-404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- leetcode(88).404. Sum of Left Leaves
- 【LeetCode】 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- [Leetcode]404. Sum of Left Leaves
- Payment:支付宝即时到账接口接入教程
- 角色的概念要根据场景进行正确的解读
- 深入Java集合系列之六:CopyOnWriteArrayList
- [BZOJ 2875][Noi2012]随机数生成器:矩阵乘法+快速乘
- C#调用带参存储过程
- leetcode 404. Sum of Left Leaves
- (转)Android JSON解析详解(详细代码)
- 一个小程序
- 用户信用卡系统
- 感性认识spring的IoC
- PL/SQL 显式游标
- offsetHeight、offsetWidth、clientWidth、clientHeight无法获取值得问题
- 有些时候,有些判断是无法做到真实,但是能做到最优也不错了
- 来谈谈SQL数据库中"简单的"SELECT TOP—可能有你从未注意到的细节