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

Leetcode题目:Binary Tree Paths

时间:2016-04-27 20:31:46      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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:
    vector<string> binaryTreePaths(TreeNode* root) {
        if(root == NULL)
            return res;
        stringstream ss;
        ss << root -> val;
        if((root -> left == NULL) && (root -> right == NULL))
        {
            res.push_back(ss.str());
            return res;
        }
        else
        {
            getPaths(root,ss.str());
        }
        return res;
    }
   
    void getPaths(TreeNode *root,string s)
    {
        if((root -> left == NULL) && (root -> right ==NULL))
        {
            res.push_back(s);
        }
        if(root -> left != NULL)
        {
            stringstream ss;
            ss << s << "->" << root -> left -> val;
            getPaths(root -> left , ss.str());
        }
        if(root -> right != NULL)
        {
            stringstream ss;
            ss << s << "->" <<  root -> right -> val;
            getPaths(root -> right , ss.str());
        }
    }
private:
    vector<string> res;
};

 

Leetcode题目:Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/CodingGirl121/p/5440096.html

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