Clean C++ solution using DFS


  • 1
    A
    class Solution {
    public:
        int dfs(vector<vector<int>> &ans, TreeNode *curr) {
            if (!curr)
                return 0;
            
            int leftHeight = dfs(ans, curr->left), rightHeight = dfs(ans, curr->right);
            int idx = max(leftHeight, rightHeight);
            if (idx == ans.size())
                ans.push_back({});
            ans[idx].push_back(curr->val);
            return idx + 1; // height
        }
    
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int>> ans;
            dfs(ans, root);
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.