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

[LeetCode257]Binary Tree Paths

时间:2016-02-29 23:11:43      阅读:147      评论: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:
    void RootPath(vector<string>& resultVec, TreeNode *root, string s)
    {
        if (root->left == NULL && root->right == NULL)
        {
            resultVec.push_back(s);
            return;
        }
        if (root->left)
        {
            RootPath(resultVec, root->left, s + "->" + to_string(root->left->val));
        }
        if (root->right)
        {
            RootPath(resultVec, root->right, s + "->" + to_string(root->right->val));
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        if (root == NULL) return result;
        RootPath(result, root, to_string(root->val));
        return result;
    }
};

 

[LeetCode257]Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5229125.html

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