LeetCode - 865. Smallest Subtree with all the Deepest Nodes

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in it's subtree.

题目第一遍看有点难懂,就是找一个节点,它能“包括”所有最深的叶节点,题目中没有提到的细节就是,如果只有一个叶节点,那么返回的是这个叶节点本身,而不是它的父节点。

Example:

https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.pngOutput: [2,7,4]

思路:

    这个是Weekly Contest的题,做的时候还没有解答,我的AC解法是,先遍历整棵树,为所有节点设置parent,顺便找出最深的节点,放入一个vector中。然后看vector中的所有节点是不是一样的,不是的话,所有节点变成自己的父节点(可以优化)。另外,如果vector中只有一个,直接返回这个node即可。

map<TreeNode*, TreeNode*> parent;
vector<TreeNode*> leaf;
    
// 设置所有节点父节点,并将所有叶子节点放入leaf
void set_Parent(TreeNode* tn, int depth, int& cur_depth)
{
    if(!tn->left && !tn->right) // leaf node
    {
        if(depth > cur_depth)
        {
            leaf.clear();
            leaf.push_back(tn);
            cur_depth = depth;
        }
        else if(depth == cur_depth)
            leaf.push_back(tn);

        return;
    }
    if(tn->left)
    {
        parent[tn->left] = tn;
        set_Parent(tn->left, depth + 1, cur_depth);
    }
    if(tn->right)
    {
        parent[tn->right] = tn;
        set_Parent(tn->right, depth + 1, cur_depth);
    }        
}
    
void UpdateNodes(vector<TreeNode*>& v)
{
    for(int i = 0, s = v.size(); i < s; i ++)
        v[i] = parent[v[i]];
}
    
TreeNode* subtreeWithAllDeepest(TreeNode* root)
{
    if(root == NULL)
        return NULL;
    if(!root->left && !root->right)
        return root;
    int cur_depth = 0;
    set_Parent(root, 1, cur_depth);
        
    int leaf_num = leaf.size();
    if(leaf_num == 0)
        return NULL;
    if(leaf_num == 1)
        return leaf[0];
    while(1)
    {
        TreeNode* tmp = leaf[0];
        int i = 1;
        for(; i < leaf_num; i++)
        {
            if(tmp != leaf[i])
            {
                UpdateNodes(leaf);
                break;
            }
        }
        if(i == leaf_num)
            return tmp;
    }
    return NULL;
}

set_parent沿用了我之前的单纯设置父节点,https://blog.csdn.net/bob__yuan/article/details/81067576,这个在 LeetCode 里的树相关题目中还是很有用的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值