• leetcode 257. Binary Tree Paths


    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"]


    1.因为要回溯,我刚开始想的就是递归,但是怎么保存之前已经走过的路径呢?
    2.又因为TreeNode存的值是int的,而需要返回string,又要如何转换呢?
    3.什么时候push_back当前的路径?
    4.什么时候返回vetcor?

    1.第一个问题,参考之前path sum的解法,我把string作为递归函数的一个参数。
    2.int和string的转换还是用stringstream进行转换的。
    3.遇到叶子节点push_back当前路径
    4.递归的函数不返回值,返回类型为void,但是在函数中修改vector而回溯到根节点递归结束,返回vector

    遇到的问题:
    1.把字符串流也设置为成员变量的时候,ss>>tmp,tmp没改变。于是改成在递归函数里初始化字符串流和字符串,只为了int转换string


    /**
     * 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> ret;
        void Path(TreeNode* root,string before){
            if(root!=NULL){
                stringstream ss;
                string tmp;
                ss<<(root->val);
                ss>>tmp;
                before+=tmp;
                if(root->left!=NULL||root->right!=NULL) before+="->";
                if(root->left!=NULL) Path(root->left,before);
                if(root->right!=NULL) Path(root->right,before);
                if(root->left==NULL&&root->right==NULL) {ret.push_back(before);return;}
        
            
        }}
        vector<string> binaryTreePaths(TreeNode* root) {
            if(root==NULL) return ret;
            string before="";
            Path(root,before);
            return ret;
        }
    };
    
    
    





  • 相关阅读:
    django目录
    django之form表单验证
    django操作数据库之查询F,Q操作 和 seach搜索功能
    django的序列化
    三目运算
    【转】做有生命力的接口测试
    【转】浅谈反应测试
    【转】jmeter 进行java request测试
    【转】探索式测试:基本概念
    【转】 测试职业思考:如何成为一名优秀的软件测试工程师
  • 原文地址:https://www.cnblogs.com/LUO77/p/5072403.html
Copyright © 2020-2023  润新知