Leecode 865. 具有所有最深节点的最小子树 DFS

原题链接:Leecode 865. 具有所有最深节点的最小子树
在这里插入图片描述
在这里插入图片描述
自己写的代码,比较复杂:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    map<TreeNode*,TreeNode*> fa;
    map<TreeNode*,int> tall;
    int res=0;
    void fun(TreeNode* root)
    {
        res=max(res,tall[root]);
        if(root->left)
        {
            tall[root->left]=tall[root]+1;
            fa[root->left]=root;
            fun(root->left);
        }
        if(root->right)
        {
            tall[root->right]=tall[root]+1;
            fa[root->right]=root;
            fun(root->right);
        }
    }
    TreeNode* Union(TreeNode* r1,TreeNode* r2)
    {
        map<TreeNode*,int> m;
        while(r1!=fa[r1])
        {
            m[r1]=1;
            r1=fa[r1];
        }
        m[r1]=1;
        while(r2!=fa[r2])
        {
            if(m[r2]) break;
            r2=fa[r2];
        }
        return r2;
    }
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        tall[root]=0;
        fun(root);
        fa[root]=root;
        vector<TreeNode*> v;
        for(auto it=tall.begin();it!=tall.end();it++)
        {
            if(it->second==res) v.push_back(it->first);
        }
        if(v.size()==1) return v[0];
        TreeNode* father=v[0];
        for(int i=1;i<v.size();i++)
        {
            father=Union(father,v[i]);
        }
        return father;
    }
};

参考别人更简洁的代码:
思路:从每个树开始,获得当前节点的左右子树的最大深度,深度相同,说明最深的节点在这个节点两边,那这个节点就是结果,如果深度不相同,则去深度大的子树继续判断,最终就能得到结果

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int height(TreeNode* root)
    {
        if(!root) return 0;
        return max(height(root->left),height(root->right))+1;
    }
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        if(!root) return root;
        int l=height(root->left);
        int r=height(root->right);
        if(l==r) return root;
        if(l>r) return subtreeWithAllDeepest(root->left);
        return subtreeWithAllDeepest(root->right); 
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值