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:

LeetCode - 865. Smallest Subtree with all the Deepest Nodes_第1张图片Output: [2,7,4]

思路:

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

map parent;
vector 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& 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 里的树相关题目中还是很有用的。

你可能感兴趣的:(LeetCode,Algorithm)