• 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"]
    代码如下:
    /**
     * 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:
        //按照容易自己习惯的数据结构来存储路径,最后做一个转换
        void findPath(TreeNode* t,vector<int>& temp, vector<vector<int> >& record)
        {
            temp.push_back(t->val);
        	if(t->left!=NULL) findPath(t->left, temp, record);
        	if(t->right!=NULL) findPath(t->right, temp, record);
        	//到达叶子节点,就记录路径
        	if(t->left==NULL && t->right==NULL)
        	{
        	    record.push_back(temp);
        	    temp.erase(temp.end()-1);
        	    return ;
        	}
        	//中间节点返回
        	temp.erase(temp.end()-1);
        	return;
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<vector<int>> record;
            vector<string> srecord;
    	    if(root==NULL) return srecord;
    	    vector<int> temp;
    	    //找到所有的路
    	    findPath(root,temp,record);
    	    //把所有的路按照题目要求存储
    	    string stemp;
    	    for(int i=0;i<record.size();i++)
    	    {
    	        stringstream ss;
    	        for(int j=0;j<record[i].size();j++)
    	        {
    	            ss<<record[i][j]<<"->";
    	        }
    	        stemp.clear();
    	        stemp=ss.str();
    	        //去掉最后的"->"
    	        stemp.pop_back();
    	        stemp.pop_back();
    	        srecord.push_back(stemp);
    	    }
    	    return srecord;
        }
    };


  • 相关阅读:
    IOS Xcode编译项目-报错“ld: library not found for -XX”
    ios中关键词weak,assign,copy.strong等的区别
    iOS 控件
    iOS图片处理
    iOS 音频
    C语言文件操作
    iOS 删除相册中照片--来自简书
    ios sourecTree
    ios音频处理
    编码格式简介
  • 原文地址:https://www.cnblogs.com/gremount/p/5768004.html
Copyright © 2020-2023  润新知