脚本宝典收集整理的这篇文章主要介绍了[leetcode] 404 559 563,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
3
/
9 20
/
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
solution
class Solution:
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)
559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root:
return 0
max_depth = 1 # 注意要初始化为1,因为此处root不为空,至少有一个节点。
for each in root.children:
depth = 1 + self.maxDepth(each)
if depth > max_depth:
max_depth = depth
return max_depth
563. Binary Tree Tilt
Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all nodes' tilt.
Input:
1
/
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.count = 0
def _sum(root):
if not root:
return 0
left = _sum(root.left)
right = _sum(root.right)
self.count += abs(left - right)
return root.val + left + right
_sum(root)
return self.count
以上是脚本宝典为你收集整理的[leetcode] 404 559 563全部内容,希望文章能够帮你解决[leetcode] 404 559 563所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。