Solution without helper function


  • 0

    The idea would be when you stand on a node, ask results from left tree and right tree.
    After that, you append the current node value together with arrow.
    if you stand on a node which doesn't have any child node, then just return this node.

    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
            if(root){
                if(!root->left&&!root->right){
                    res.push_back(to_string(root->val));
                }
                else{
                    vector<string> l=binaryTreePaths(root->left);
                    vector<string> r=binaryTreePaths(root->right);
                    string t=to_string(root->val)+"->";
                    for(auto& s: l)
                        res.emplace_back(t+s);
                    for(auto& s: r)
                        res.emplace_back(t+s);
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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