C++ solution for binary tree paths


  • 0
    G
    class Solution {
    private:
        vector<string> result;
    public:
        
        vector<string> binaryTreePaths(TreeNode* root) {
            if(root==NULL)return result;
            string str=to_string(root->val);
            check(root,str);
            return result;
        }
        void check(TreeNode* root,string str){
            string newStr=str;
            if(root->left==NULL&&root->right==NULL){
                result.push_back(newStr);return;
            }
            if(root->left!=NULL)
                check(root->left,newStr+"->"+to_string(root->left->val));
            if(root->right!=NULL)
                check(root->right,newStr+"->"+to_string(root->right->val));
        }
    };

Log in to reply
 

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