[C++] A clean one function approach


  • 7
    X
    vector<string> binaryTreePaths(TreeNode* root) {
      if (root == nullptr)
        return {};
      if (root->left == nullptr && root->right == nullptr)
        return {to_string(root->val)};
    
      vector<string> left  = binaryTreePaths(root->left);
      vector<string> right = binaryTreePaths(root->right);
      left.insert(left.end(), begin(right), end(right));
      for (auto &e : left)
        e = to_string(root->val) + "->" + e;
      return left;
    }

  • 0

    What do the {}'s do on the returns on lines 3 and 5? Why do the values need to be wrapped in curly braces?


  • 0
    X

    Since C++11, you can initialize a vector, for example, like this: vector<int> foo{1, 2, 3, 4}. In my code, I'm returning vector<string>. return {} returns an empty vector<string>. See: http://en.cppreference.com/w/cpp/utility/initializer_list


  • 0

    Ah I see, thanks!


  • 0
    P

    That's pretty nice!


Log in to reply
 

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