码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--257.Binary Tree Paths

时间:2017-08-04 00:27:16      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:http   条件   iterator   etc   方法   深度   搜索   ret   return   

技术分享

使用深度优先搜索的方法遍历每一条枝,遍历完的终止条件为左右子树都为空,这时候将这条枝的string 插入vector 中。

技术分享

class Solution {
public:
// vector 一直插入string,所以为引用类型,string不能是引用类型
    void dfs(TreeNode *root, vector<string> & result, string temp)
    {
        if(root->left==NULL&&root->right==NULL)
            result.push_back(temp);
        if(root->left)
            dfs(root->left,result,temp+"->"+to_string(root->left->val));
        if(root->right)
            dfs(root->right,result,temp+"->"+to_string(root->right->val));
    }
        
        
        
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string>result;
        if(root==NULL)
            return result; 
        
        string temp=to_string(root->val);
        dfs(root, result, temp);
        
        return result;
        
    
        
    }
};

  第二种方法,在函数内部进行递归:

技术分享

 

vector<string> binaryTreePaths(TreeNode *root)
    {
        vector<string> result;
       
        if(root==NULL)
            return result;
        
        if(root->left==NULL&& root->right==NULL)
            return {to_string(root->val)};
            
        vector<string> left=binaryTreePaths(root->left);
        vector<string> right=binaryTreePaths(root->right);
        
        left.insert(left.end(),right.begin(),right.end());
        vector<string>::iterator iter;
        for(iter=left.begin();iter!=left.end();iter++)
        {
            *iter=to_string(root->val)+"->"+*iter;
        }
        return left;
    }

  

 

leetcode--257.Binary Tree Paths

标签:http   条件   iterator   etc   方法   深度   搜索   ret   return   

原文地址:http://www.cnblogs.com/fanhaha/p/7282685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!