给定一个根为 root 的二叉树,每个结点的深度是它到根的最短距离。
如果一个结点在整个树的任意结点之间具有最大的深度,则该结点是最深的。
一个结点的子树是该结点加上它的所有后代的集合。
返回能满足“以该结点为根的子树中包含所有最深的结点”这一条件的具有最大深度的结点。
示例:
输入:[3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
解释:
我们返回值为 2 的结点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的结点。
输入 "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" 是对给定的树的序列化表述。
输出 "[2, 7, 4]" 是对根结点的值为 2 的子树的序列化表述。
输入和输出都具有 TreeNode 类型。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1.
class Solution {
public:
int depth(TreeNode* root) {
if (root == NULL) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
if (root == NULL) return root;
int dl = depth(root->left);
int dr = depth(root->right);
if (dl == dr) return root;
if (dl > dr) return subtreeWithAllDeepest(root->left);
return subtreeWithAllDeepest(root->right);
}
};
作者:da-li-wang
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/solution/c-jian-dan-di-gui-by-da-li-wang-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2.
class Solution {
public:
pair<int, TreeNode*> dfs(TreeNode* root, int d) {
if (root == NULL) return {-1, root};
if (root->left == NULL && root->right == NULL) return {d, root};
auto pl = dfs(root->left, d + 1);
auto pr = dfs(root->right, d + 1);
if (pl.first < pr.first) return pr;
if (pl.first > pr.first) return pl;
return {pl.first, root};
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(root, 0).second;
}
};
作者:da-li-wang
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/solution/c-jian-dan-di-gui-by-da-li-wang-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。