C++ O(N) solution


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

Log in to reply
 

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