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

leetcode:Binary Tree Paths

时间:2015-08-17 17:25:01      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:leetcode   binarytree   深度搜索   

Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:
技术分享
All root-to-leaf paths are:[“1->2->5”, “1->3”]

分析
深度搜索

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> ret;
        string str;
        dfs(ret, str, root);
        return ret;
    }
    void dfs(vector<string>& ret, string& str, TreeNode* root){
        if (!root)
            return;
        if (root && !root->left&&!root->right){
            str+=to_string(root->val);
            ret.push_back(str);
            return;
        }
        string tmp = str;
        str += to_string(root->val)+"->";
        if (root->left)
            dfs(ret, str, root->left);
        str = tmp;

        tmp = str;
        str += to_string(root->val) + "->";
        if (root->right)
            dfs(ret, str, root->right);
        str=tmp;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode:Binary Tree Paths

标签:leetcode   binarytree   深度搜索   

原文地址:http://blog.csdn.net/lmingyin5/article/details/47726725

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