4ms c++ solution with preorder traversal (easy to understand)


  • 0
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
            if(root==NULL)
                return res;
            vector<int> path;
            binaryTreePathsCore(root, path, res);
            return res;
        }
        void binaryTreePathsCore(TreeNode* root, vector<int>& path, vector<string>& res)
        {
            path.push_back(root->val);
            if(root->left==NULL && root->right==NULL)
            {
                string str;
                for(auto i : path)
                    str += to_string(i) + "->";
                str = str.substr(0, str.length()-2);
                res.push_back(str);
            }
            if(root->left!=NULL)
                binaryTreePathsCore(root->left, path, res);
            if(root->right!=NULL)
                binaryTreePathsCore(root->right, path, res);
            path.pop_back();
        }
    };

Log in to reply
 

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