Naive 4ms C++ solution with dummy root. Slower but easier to understand.


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

Log in to reply
 

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