小黑代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
self.max_depth = 0
self.max_depth_nodes = []
# 获得结点孩子数组
def dfs(node, arr):
if not node:
return
arr.append(node)
dfs(node.left, arr)
dfs(node.right, arr)
# 求二叉树每个节点的深度
def get_depth(node, depth=0):
if not node:
return
depth += 1
if depth > self.max_depth:
self.max_depth_nodes = [node]
self.max_depth = depth
elif depth == self.max_depth:
self.max_depth_nodes.append(node)
get_depth(node.left, depth)
get_depth(node.right, depth)
get_depth(root)
self.target_node = None
# 后跟遍历,求最深公共结点
def after_dfs(node):
if not node:
return
after_dfs(node.left)
after_dfs(node.right)
if self.target_node:
return
arr = []
dfs(node,arr)
flag = True
for node_ in self.max_depth_nodes:
if node_ not in arr:
# print(node_,arr)
flag = False
break
if flag:
self.target_node = node
after_dfs(root)
return self.target_node
两次深度优先
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
depth_map = {}
self.max_depth = 0
def dfs(node, depth):
if not node:
return
depth += 1
if self.max_depth < depth:
self.max_depth = depth
depth_map[node] = depth
dfs(node.left, depth)
dfs(node.right, depth)
# 计算depth_map
dfs(root, 0)
# 获取结果
def result(node):
if not node:
return
# 获取左右子树的包含max_depth的最小子树
left_node = result(node.left)
right_node = result(node.right)
# 结点是最深结点
if depth_map[node] == self.max_depth:
return node
# 左右子树都包含max_depth结点
if left_node and right_node:
return node
if left_node:
return left_node
if right_node:
return right_node
return None
return result(root)
一次优先搜索
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
class Result(object):
def __init__(self, node = None, dist = 0):
self.node = node
self.dist = dist
def dfs(node):
# 结点不存在
if not node:
return Result()
left_result = dfs(node.left)
right_result = dfs(node.right)
# 左子树深的话,返回左子树下最深结点的最小子树
if left_result.dist > right_result.dist:
return Result(node=left_result.node, dist=left_result.dist + 1)
if left_result.dist < right_result.dist:
return Result(node=right_result.node, dist=right_result.dist + 1)
return Result(node=node, dist=right_result.dist + 1)
return dfs(root).node
小黑生活
发现了个学git的小神器
晚饭外卖
晚上开始哈农的学习
早餐牛排
早上运动
公司团建烤肉肉
午餐咖啡&&晚餐
晚间按摩一个半
早餐牛排&&跑步
午餐+聊天