zoukankan      html  css  js  c++  java
  • leetcode--257.Binary Tree Paths

    使用深度优先搜索的方法遍历每一条枝,遍历完的终止条件为左右子树都为空,这时候将这条枝的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;
        }
    

      

  • 相关阅读:
    利用Cubieborad破解WiFi
    从零开始——Mysql备份还原数据库
    从零开始——Ubuntu系统安装redis和phpredis
    监控应用卡顿BlockCanary
    2.AS内存分析
    热修复原理
    MultiDex 原理
    APP启动时白屏优化及multidex优化
    线程池的简便记忆方法
    2.volatile和AtomicXX
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7282685.html
Copyright © 2011-2022 走看看