104 二叉树的最大深度

``````# 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 maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
q = [root]
stash = []
ans = 0
while q:
r = q.pop()
if r.left:
stash.append(r.left)
if r.right:
stash.append(r.right)
if len(q) == 0:
q = stash
ans += 1
stash = []
return ans
``````

1123 最深叶节点的最近公共祖先

``````# 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):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def dfs(root):
if not root:
return None, 0
lr, ld = dfs(root.left)
rr, rd = dfs(root.right)
if ld > rd:
return lr, ld + 1
elif ld < rd:
return rr, rd + 1
else:
return root, ld + 1
ans, h = dfs(root)
return ans
``````

865 具有所有最深节点的最小子树

``````# 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 subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def f(root):
if not root:
return None, 0
l, r = f(root.left), f(root.right)
if l[1] > r[1]:
return l[0], l[1] + 1
elif l[1] < r[1]:
return r[0], r[1] + 1
else:
return root, r[1] + 1
return f(root)[0]
``````