【树】257. 二叉树的所有路径

257. 二叉树的所有路径

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

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

递归实现

vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root==NULL) return res;
        change(root,res,"");
        return res;
    }
    void  change(TreeNode* root,vector<string> &res,string path){
        if(root==NULL) return;
        path+=to_string(root->val);
        if(root->left==NULL&&root->right==NULL){
            res.push_back(path);
            return;
        }
        if(root->left) change(root->left,res,path+"->");
        if(root->right) change(root->right,res,path+"->");
    }
posted @ 2020-04-29 11:33  爱吃猫的鱼69  阅读(146)  评论(0)    收藏  举报