leetcode-257-binary tree paths

Problem Description:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   
2     3
 
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

题目大意:

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

Solutions:

利用深度优先搜索,每当走到叶子节点便返回路径。

Code in C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if(root)
            dfs(root,res,"");
        return res;
    }
    void dfs(TreeNode* root, vector<string> &res, string path){
        path+=to_string(root->val);
        if(!root->left&&!root->right)
            res.push_back(path);
        else {
            if(root->left)
                dfs(root->left,res,path+"->");
            if(root->right)
                dfs(root->right,res,path+"->");
        }
    }
};