Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> vecRet;
            if (root == NULL) return vecRet;
            string s = "";
            getTreePaths(vecRet, s, root);
            
            return vecRet;
        }
        void getTreePaths(vector<string> &vecRet, string s, TreeNode *root) {
            if (root == NULL) return;
            
            s += to_string(root->val);
            if (root->left == NULL && root->right == NULL)//the current node is leaf,then put s into vecRet
                vecRet.push_back(s);
            else
                s += "->";
    
            getTreePaths(vecRet, s, root->left);//recur in left subtree
            getTreePaths(vecRet, s, root->right);//recur in right subtree
        }
    };

Log in to reply
 

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