easy to understand C++ recursive solution


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int>> res;
            vector<int> temp;
            while(root != NULL)
            {
                helper(root, temp);
                res.push_back(temp);
                temp.clear();
            }
            return res;
        }
        void helper(TreeNode*& root, vector<int>& temp)
        {
            if(root->left == NULL && root->right == NULL)
            {
                temp.push_back(root->val);
                root = NULL;
                return;
            }
            if(root->left != NULL)
                helper(root->left, temp);
            if(root->right != NULL)
                helper(root->right, temp);
        }
    };
    

Log in to reply
 

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