4ms simple C++ solution


  • 7
    Y
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
    
            if(!root) return res;
            else if(!root->left && !root->right) res.push_back(to_string(root->val));
            
            string head = to_string(root->val) + "->";
            
            for(auto item: binaryTreePaths(root->left)) res.push_back(head + item);
            for(auto item: binaryTreePaths(root->right)) res.push_back(head + item);
            
            return res;
        }
    };
    
    

  • 0
    This post is deleted!

  • 0
    R

    @r.gupta8493gmail.com

    @r.gupta8493gmail.com said in 4ms simple C++ solution:

    good job !!!

    please review my java solution for this .. Thanks


  • 1
    J

    for(auto item: binaryTreePaths(root->left)) res.push_back(head + item);
    for(auto item: binaryTreePaths(root->right)) res.push_back(head + item);
    haven't seen this before. what does it mean?


  • 1
    I

    It can be faster a bit by early returning in

    if(!root->left && !root->right) { res.push_back(to_string(root->val)); return res; }

  • 0
    C

    Same question with Joe297, can someone explain the usage of auto ?

    I know some simple cases that can save some work to initiate a iterator through keyword auto, but here :

    for(auto item: binaryTreePaths(root->left)) res.push_back(head + item);
    for(auto item: binaryTreePaths(root->right)) res.push_back(head + item);
    

    these two syntax is really out of my scope.

    Thank you guys.


  • 1
    I

    @concertttttt

    It's quite equivalent to:

    
    auto& pathsLeft = binaryTreePaths(root->left);
    for (auto item: pathsLeft) res.push_back(head + item);
    

  • 0
    X

    short but time-consuming


Log in to reply
 

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