zoukankan      html  css  js  c++  java
  • Leetcode(257)-二叉树的所有路径

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

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

    示例:

    输入:
    
       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;
    }
  • 相关阅读:
    抽取幸运观众
    随机产生139开头的电话号码
    脚本同步服务器系统时间
    判断网页是否存活
    nginx 添加到环境变量中
    spring boot helloworld
    IDEA 2019.3.3 Maven配置
    Window IDEA ULTIMATE 2019.3.3 安装&配置
    centos 7 Jenkins版本升级
    window 10 vscode+vue配置
  • 原文地址:https://www.cnblogs.com/mini-coconut/p/9326454.html
Copyright © 2011-2022 走看看