1123 Lowest Common Ancestor of Deepest Leaves 最深叶节点的近来公共先人
Description:
Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
The node of a binary tree is a leaf if and only if it has no children
The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.
The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.
Example:
Example 1:
[图片上传失败...(image-41d2a4-1650928374413)]
Input: root = [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 coloured in blue are the deepest leaf-nodes of the tree.
Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
Example 2:
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree, and it's the lca of itself.
Example 3:
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.
Constraints:
The number of nodes in the tree will be in the range [1, 1000].
0 <= Node.val <= 1000
The values of the nodes in the tree are unique.
Note:
This question is the same as 865
标题形貌:
给你一个有根节点 root 的二叉树,返回它 最深的叶节点的近来公共先人 。
追念一下:
叶节点 是二叉树中没有子节点的节点
树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
如果我们假定 A 是一组节点 S 的 近来公共先人,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度到达此条件下大概的最大值。
示例 :
示例 1:
[图片上传失败...(image-161aa9-1650928374413)]
输入:root = [3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
表明:我们返回值为 2 的节点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的节点。
注意,节点 6、0 和 8 也是叶节点,但是它们的深度是 2 ,而节点 7 和 4 的深度是 3 。
示例 2:
输入:root = [1]
输出:[1]
表明:根节点是树中最深的节点,它是它自己的近来公共先人。
示例 3:
输入:root = [0,1,3,null,2]
输出:[2]
表明:树中最深的叶节点是 2 ,近来公共先人是它自己。
提示:
树中的节点数将在 [1, 1000] 的范围内。
0 <= Node.val <= 1000
每个节点的值都是 独一无二 的。
注意:
本题与力扣 865 重复
思绪:
DFS
这标题也太绕了, 题意是找到一棵树, 这棵树上全部的结点或者子结点包罗深度最深的叶子结点
实在就是找到左子树和右子树高度相称的根结点
对每个结点查找高度即可
时间复杂度为 O(n), 空间复杂度为 O(n)
代码:
C++: |