给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。
回想一下:
叶节点 是二叉树中没有子节点的节点
树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。示例 1:
输入:root = [1,2,3]
输出:[1,2,3]
解释:
最深的叶子是值为 2 和 3 的节点。
这些叶子的最近共同祖先是值为 1 的节点。
返回的答案为序列化的 TreeNode 对象(不是数组)"[1,2,3]" 。1.字节面试题
递归
二值dfs这种思想可以学习一下!
class Solution:def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:def get_depth(root):if not root:return 0return max(get_depth(root.left),get_depth(root.right))+1def dfs(root):l=get_depth(root.left)r=get_depth(root.right)if not root or (root and not root.left and not root.right) or l==r:return rootreturn dfs(root.left) if l>r else dfs(root.right)return dfs(root)
class Solution:def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:def dfs(root):if not root:return None, 0lr, ld = dfs(root.left)rr, rd = dfs(root.right)if ld > rd:return lr, ld + 1elif ld < rd:return rr, rd + 1else:return root, ld + 1ans, h = dfs(root)return ans