0 ms easy to understand C++ solution(destructive) without using level/height


  • 0
    C
    class Solution {
    public:
        bool isLeaf(TreeNode *r, vector<int> &t) {
            if(!r)
                return false;
                
            if(!r->left && !r->right) {
                t.push_back(r->val);
                return true;
            }
            
            if(isLeaf(r->right, t))
                r->right = nullptr;
                
            if(isLeaf(r->left, t))
                r->left = nullptr;
            
            return false;
        }
        vector<vector<int>> findLeaves(TreeNode* r) {
            vector<vector<int>> ret;
            vector<int> t;
            while(r) {
                if(isLeaf(r, t))
                    r = nullptr;
                ret.push_back(t);
                t.clear();
            }
            return ret;
        }
    };
    
    

Log in to reply
 

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