4 msec C++ solution w/o modifying the tree


  • 0
    S
    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> leaves;
        unordered_set<TreeNode *> visited;
        
        visited.insert(NULL);
        while (visited.find(root) == visited.end()) {
            leaves.clear();
            dfs(root, visited, leaves);
            res.push_back(leaves);
        }
        
        return res;
    }
    
    void dfs(TreeNode *root, unordered_set<TreeNode *> &visited, vector<int> &leaves) {
        if (visited.count(root)) return;
        if (visited.count(root->left) && visited.count(root->right)) {
            leaves.push_back(root->val);
            visited.insert(root);
            return;
        }
        dfs(root->left, visited, leaves);
        dfs(root->right, visited, leaves);
    }

Log in to reply
 

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