加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode 366. Find Leaves of Binary Tree

发布时间:2020-12-14 03:47:08 所属栏目:大数据 来源:网络整理
导读:实质就是求每个节点的最大深度。用一个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); // fo

实质就是求每个节点的最大深度。用一个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;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读