Leetcode题目: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:
    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;
};

 

posted @ 2016-04-27 19:29  CodingGirl121  阅读(154)  评论(0编辑  收藏  举报