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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

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

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

思路:要求所有路径这种所有解问题,要想到深度优先遍历。这里我们采用深入优先遍历,递归的方式来实现。其中涉及到int型转string型的知识。

int转string。

(1)c++中的<string>中提供了to_string函数,string to_string(int value)的形式,但是在VS2010的编译器中,会报错。这里还有第二种方法

(2)string还有一种方法

string to_string(int i){
  stringstream os;
  os<<i;
  return os.str();
 }
string Int_to_String(int n)
{
    ostringstream os;
    os<<n; //n为int类型
    return os.str();
}
void helper(TreeNode* root,vector<string>&str,string path)
{
    if(root->left==NULL && root->right==NULL)
    {
        str.push_back(path);
        return;
    }
    if(root->left)
    {
        helper(root->left,str,path+"->"+Int_to_String(root->left->val));
    }
    if(root->right)
    {
        helper(root->right,str,path+"->"+Int_to_String(root->right->val));
    }
}
vector<string> binaryTreePaths(TreeNode* root) 
{
    vector<string> res;
    if(root==NULL)
        return res;
    helper(root,res,Int_to_String(root->val));//这里每次都提前将该节点的值加进去
    return res;
}

 

posted on 2018-07-17 22:43  Mini_Coconut  阅读(140)  评论(0编辑  收藏  举报