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;
        }
    };


  • 相关阅读:
    ipv6 for openwrt odhcpd
    openwrt package Makefile
    openwrt 中个网络接口协议说明[转]
    openwrt Package aircrack-ng is missing dependencies for the following libraries:
    linux kernel 从cmdline 提取值
    js 上传文件进度条 [uboot使用]
    printk打印级别 [转]
    linux c 宏定义
    uboot 开发记录
    mac ssh scp命令
  • 原文地址:https://www.cnblogs.com/gremount/p/5768004.html
Copyright © 2011-2022 走看看