【ACM从零开始】LeetCode OJ-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"]
题目大意:给出一个二叉树,输出前序遍历的信息。
解题思路:基础题,用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);
    }
};
posted @ 2015-10-07 17:01  Shvier  阅读(162)  评论(0编辑  收藏  举报