LeetCode 366. Find Leaves of Binary Tree

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 366. Find Leaves of Binary Tree相关的知识,希望对你有一定的参考价值。

实质就是求每个节点的最大深度。用一个hash表记录,最后输出。

class Solution {
public:
    unordered_map<TreeNode *,int> hash; // record the level from bottom
    
    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        dfs(root);
        //for (auto x:hash) cout << x.first->val << ‘ ‘ << x.second << endl;
        for (int i=1;i<=hash[root];++i){
            vector<int> tmp;
            for (auto x:hash){
                if (x.second==i)
                    tmp.push_back(x.first->val);
            }
            res.push_back(tmp);
        }
        return res;
    }
    
    int dfs(TreeNode *root){
        if (root==NULL) return 0;
        int depth=max(dfs(root->left),dfs(root->right))+1;
        hash[root] = depth;
        return depth;
    }
};

 

其实可以不用hash表,每次深度比vector.size()大的时候新建一个vector,这样节省了空间。

类似的方法在别的题里也有应用。

class Solution {
public:
    vector<vector<int>> res;
    
    vector<vector<int>> findLeaves(TreeNode* root) {
        dfs(root);
        return res;
    }
    
    int dfs(TreeNode *root){
        if (root==NULL) return 0;
        int depth=max(dfs(root->left),dfs(root->right))+1;
        if (depth>res.size()) res.push_back(vector<int>());
        res[depth-1].push_back(root->val);
        return depth;
    }
};

 

以上是关于LeetCode 366. Find Leaves of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 366. Find Leaves of Binary Tree

366. Find Leaves of Binary Tree

366. Find Leaves of Binary Tree

366. Find Leaves of Binary Tree

366. Find Leaves of Binary Tree C#

LeetCode Find Leaves of Binary Tree