257. 二叉树的所有路径

给定一个二叉树,返回所有从根节点到叶子节点的路径。
先序遍历

void iterator(TreeNode* root,vector<string> &res,string s){           
            if(s.empty()) s += to_string(root->val);     
            else s+="->" + to_string(root->val);
            if (root->left == NULL && root->right == NULL)            
                res.push_back(s);         
            if (root->left != NULL)            
                iterator(root->left,res,s);         
            if (root->right != NULL)            
                iterator(root->right,res,s);     
        }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root == NULL) return res;
        string s;
        iterator(root, res, s);
        return res;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容