给定一个根为 root 的二叉树,每个节点的深度是 该节点到根的最短距离 。
返回包含原始树中所有 最深节点 的 最小子树 。
如果一个节点在 整个树 的任意节点之间具有最大的深度,则该节点是 最深的 。
一个节点的 子树 是该节点加上它的所有后代的集合。
Given the root of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
解释:
我们返回值为 2 的节点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的节点。
注意,节点 5、3 和 2 包含树中最深的节点,但节点 2 的子树最小,因此我们返回它。
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 nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.
示例 2:
输入:root = [1]
输出:[1]
解释:根节点是树中最深的节点。
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree.
示例 3:
输入:root = [0,1,3,null,2]
输出:[2]
解释:树中最深的节点为 2 ,有效子树为节点 2、1 和 0 的子树,但节点 2 的子树最小。
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.
提示:
Constraints:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var subtreeWithAllDeepest = function (root) {
return f(root)[1]
};
function f(root) {
if (!root) {
return [0, root]
}
let [d1, cal1] = f(root.left)
let [d2, cal2] = f(root.right)
if (d1 > d2) {
return [d1 + 1, cal1]
}
if (d2 > d1) {
return [d2 + 1, cal2]
}
return [d1 + 1, root]
}
解题:
方法一:递归
思路与算法
题目给出一个二叉树,要求返回它最深的叶节点的最近公共祖先。其中树的根节点的深度为 0,我们注意到所有深度最大的节点,都是树的叶节点。为方便说明,我们把最深的叶节点的最近公共祖先,称之为lca 节点。
我们用递归的方式,进行深度优先搜索,对树中的每个节点进行递归,返回当前子树的最大深度 d 和 lca 节点。如果当前节点为空,我们返回深度 0 和空节点。在每次搜索中,我们递归地搜索左子树和右子树,然后比较左右子树的深度:
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-deepest-leaves/solutions/2421007/zui-shen-xie-jie-dian-de-zui-jin-gong-go-cjzv/
注意:本题与力扣 1123 重复:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves
leetcode:https://leetcode.cn/problems/smallest-subtree-with-all-the-deepest-nodes/