二叉树的所有路径-LintCode

来源:互联网 发布:淘宝店解封后有影响吗 编辑:程序博客网 时间:2024/06/06 07:48

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例:
给出下面这棵二叉树:

   1 /   \2     3 \  5

所有根到叶子的路径为:

[  "1->2->5",  "1->3"]
#ifndef C480_H#define C480_h#include<iostream>#include<vector>#include<string>using namespace std;class TreeNode{public:    int val;    TreeNode *left, *right;    TreeNode(int val)    {        this->val = val;        this->left = this->right = NULL;    }};class Solution {public:    /*    * @param root: the root of the binary tree    * @return: all root-to-leaf paths    */    vector<string> binaryTreePaths(TreeNode * root) {        // write your code here        vector<string> vstr;        if (root == NULL)            return vstr;        build(vstr, root, "");        return vstr;    }    void build(vector<string> &vstr, TreeNode *root,string str)    {        if (root==NULL)        {            return;        }        if (str.empty())            str += to_string(root->val);        else            str += ("->" + to_string(root->val));        if (root->left == NULL&&root->right == NULL)            vstr.push_back(str);        build(vstr, root->left, str);        build(vstr, root->right, str);    }};#endif