中卫企业管理培训网站,基于php的图书管理系统论文,爱做网站免费版,做网站的流量怎么算钱给定一个根为 root 的二叉树#xff0c;每个节点的深度是 该节点到根的最短距离 。
返回包含原始树中所有 最深节点 的 最小子树 。
如果一个节点在 整个树 的任意节点之间具有最大的深度#xff0c;则该节点是 最深的 。
一个节点的 子树 是该节点加上它的所有后代的集合…给定一个根为 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.提示
树中节点的数量在 [1, 500] 范围内。0 Node.val 500每个节点的值都是 独一无二 的。
Constraints:
The number of nodes in the tree will be in the range [1, 500].0 Node.val 500The values of the nodes in the tree are unique.
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val (valundefined ? 0 : val)* this.left (leftundefined ? null : left)* this.right (rightundefined ? 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 和空节点。在每次搜索中我们递归地搜索左子树和右子树然后比较左右子树的深度
如果左子树更深最深叶节点在左子树中我们返回 {左子树深度 1左子树的 lca 节点}如果右子树更深最深叶节点在右子树中我们返回 {右子树深度 1右子树的 lca 节点}如果左右子树一样深左右子树都有最深叶节点我们返回 {左子树深度 1当前节点} 最后我们返回根节点的 lca 节点即可。
链接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
leetcodehttps://leetcode.cn/problems/smallest-subtree-with-all-the-deepest-nodes/