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;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9583602.html