zoukankan      html  css  js  c++  java
  • 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;
        }
    };


  • 相关阅读:
    Java反射----------------判断对象是否为空
    docker安装MongoDB创建用户,并用工具Robo连接简单CRUD
    Ubuntu 配置ip地址
    java时间的处理
    oracle my2_ep解密
    oracle 查询前7天的数据
    多表修改和多表删除
    迭代器遍历Map、List、Set
    冒泡排序
    Java有那两类异常?
  • 原文地址:https://www.cnblogs.com/gremount/p/5768004.html
Copyright © 2011-2022 走看看