LeetCode 具有所有最深节点的最小子树(递归)

版权声明:本文为博主原创文章,博客地址:https://blog.csdn.net/qq_41855420,未经博主允许不得转载。 https://blog.csdn.net/qq_41855420/article/details/91346979

给定一个根为 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 类型。

提示:

树中结点的数量介于 1 和 500 之间。
每个结点的值都是独一无二的。

\color{blue}思路分析: 对于求一棵树的最大深度,只需要利用递归算法即可,

depth(root) = 1 + max(depth(root->left), depth(root->right));

如果depth(root->left) == depth(root->right),则root必定是结果节点(因为需要同时需要包含left、right子树)
如果depth(root->left) > depth(root->right),则深度最大的子树在root->left
否则深度最大的子树在root->right。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        if(root == NULL) {
            return root;
        }
        int leftDeep = depth(root->left), rightDeep = depth(root->right);
        if(leftDeep == rightDeep) {
        //root必定是结果节点(因为需要同时需要包含left、right子树)
            return root;
        }
        else if(leftDeep > rightDeep) {
        //深度最大的子树在root->left
            return subtreeWithAllDeepest(root->left);
        }
        else{
        //否则深度最大的子树在root->right。
            return subtreeWithAllDeepest(root->right);
        }
    }
    //获取以root为根的子树的最大升读
    int depth(TreeNode *root){
        if(root == NULL) {
            return 0;
        }
        return 1 + max(depth(root->left), depth(root->right));
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/91346979