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

【leetcode】 257. Binary Tree Path

时间:2015-08-21 17:09:34      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:leetcode   binary tree   tranverse   

/**
 * @author        johnsondu
 * @time          2015.8.21 16:30
 * @description   tranverse a tree
 * @url           https://leetcode.com/problems/binary-tree-paths/
 */ 

/**
 * 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 tranverse(TreeNode *child, string str, vector<string> &vec) {
        if(str == "") str += to_string(child->val);
        else str += ("->" + to_string(child->val));
        
        if(!child->left && !child->right) {
            vec.push_back(str);
            return;
        }
        
        if(child->left) tranverse(child->left, str, vec);
        if(child->right) tranverse(child->right, str, vec);
    }
    
    vector<string> binaryTreePaths(TreeNode* root) {
        TreeNode *head = root;
        vector<string> ans;
        if(!head) return ans;
        
        string cnt("");
        tranverse(head, cnt, ans);
        return ans;
    }
};

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

【leetcode】 257. Binary Tree Path

标签:leetcode   binary tree   tranverse   

原文地址:http://blog.csdn.net/zone_programming/article/details/47836637

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