Given a binary tree rooted at root
, the depth of each node is the shortest distance to the root.
A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in it's subtree.
Example 1:
Input: [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes colored in blue are the deepest nodes of the tree. The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree. The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2. Both the input and output have TreeNode type.
Note:
- The number of nodes in the tree will be between 1 and 500.
- The values of each node are unique.
说什么求什么,暴力求出所有叶子节点的path就什么都好办
直接用LC的Run code真的对数这种数据结构还是挺好调试代码的
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
d,p = {},[]
def dfs(r):
if not r.left and not r.right:
p.append(r)
d[r] = list(p)
p.pop()
return
p.append(r)
if r.left: dfs(r.left)
if r.right: dfs(r.right)
p.pop()
dfs(root)
max_d = max([len(t) for t in d.values()])
all_node = [k for k in d.keys() if len(d[k])==max_d]
i = 0
while i<len(d[all_node[0]]):
tmp = [d[k][i] for k in all_node]
if all(tmp[j]==tmp[0] for j in range(len(tmp))):
i+=1
else:
break
return d[all_node[0]][i-1]