首页 > 其他 > 详细

【ACM从零开始】LeetCode OJ-Binary Tree Paths

时间:2015-10-07 17:29:58      阅读:169      评论: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"]
题目大意:给出一个二叉树,输出前序遍历的信息。
解题思路:基础题,用DFS搜索即可。
AC代码:
class Solution
{
public:
    vector<string> binaryTreePaths(TreeNode* root)
    {
        vector<string> path;
        DFS(root,path,"");
        return path;
    }
   
    void DFS(TreeNode* root,vector<string>& path,string ans)
    {
        if(!root)
            return;
        ans += to_string(root->val);
        if(root->left)
            DFS(root->left,path,ans+"->");
        if(root->right)
            DFS(root->right,path,ans+"->");
        if(!root->left && !root->right)
            path.push_back(ans);
    }
};

【ACM从零开始】LeetCode OJ-Binary Tree Paths

原文:http://www.cnblogs.com/shvier/p/4858956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!