C++ easy understand 0ms solution


  • 1
    R
    class Solution {
    public:
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int>> res;
            if(!root)   return res;
            while(root->left || root->right){
                vector<int> v;
                TreeNode* temp = root;
                leaves(temp, v);
                res.push_back(v);
            }
            res.push_back({root->val});
            return res;
        }
        void leaves(TreeNode* root, vector<int>& v){
            if(root->left && !root->left->right && !root->left->left){
                v.push_back(root->left->val);
                root->left = nullptr;
            }
            if(root->right && !root->right->right && !root->right->left){
                v.push_back(root->right->val);
                root->right = nullptr;
            }
            if(root->right) leaves(root->right, v);
            if(root->left)  leaves(root->left, v);
        }
    };
    

Log in to reply
 

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