543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
# 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 diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans=1
def dfs(root):
if root is None:
return 0
L=dfs(root.left)
R=dfs(root.right)
self.ans=max(self.ans,L+R+1)
return max(L,R)+1
dfs(root)
return self.ans-1
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:
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
思路:采用层序遍历,最后返回总层数
"""
# 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
"""
res=[]
if root is None:
return 0
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 len(res)
637. Average of Levels in Binary Tree
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
思路:采用层序遍历
# 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 averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
res=[]
if root is None:
return []
q=[root]
while q:
res.append([node.val for node in q])
new_q=[]
for node in q:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
q=new_q
rt=[]
for i in range(len(res)):
rt.append(float(sum(res[i]))/len(res[i]))
return rt