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.
计算给定二叉树的所有左叶子之和。
思路:
就是对每个节点,判断其是不是左节点+叶子节点,递归进行
# 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
"""
def isleaf(root):
if root.left is None and root.right is None:
return True
if root is None:
return 0
res=0
if root.left and isleaf(root.left):
res+=root.left.val
res+=self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)
return res
429. N-ary Tree Level Order Traversal
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary
tree:
We should return its level order traversal:
[ [1], [3,2,4], [5,6] ]
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
res=[]
if root is None:
return res
q=[root]
while q:
n=len(q)
ans=[]
for i in range(n):
t=q.pop(0)
ans.append(t.val)
for c in t.children:
q.append(c)
res.append(ans)
return res