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

Binary Tree Paths

时间:2015-08-29 12:39:57      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:c++   代码      



        该题采用深搜就可以做了(其实树的很多问题用深搜的思路都可以解决的),从根节点开始记录路径上的每一个节点,每到一个叶子节点把路径放入结果vector中就可以了。

/**
 * 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:

    string int2str(int src){
        stringstream dst;
        dst << src;
        return dst.str();
    }

    void execTraverl(TreeNode* root, vector<string> &result, string tmp){
        if(root -> left == nullptr && root -> right == nullptr){
            tmp += "->";
            tmp += int2str(root -> val);
            result.push_back(tmp);
            return;
        }
            
        if(root -> left != nullptr){
            string tmp1 = tmp;
            tmp1 += "->";
            tmp1 += int2str(root -> val);
            execTraverl(root -> left, result, tmp1);
        }
        
        if(root -> right != nullptr){
            string tmp2 = tmp;
            tmp2 += "->";
            tmp2 += int2str(root -> val);
            execTraverl(root -> right, result, tmp2);
        }
    }
    vector<string> binaryTreePaths(TreeNode* root){
        string tmp;
        vector<string> result;
        
        if(root == nullptr)
            return result;
        
        if(root -> left == nullptr && root -> right == nullptr){
            tmp += int2str(root -> val);
            result.push_back(tmp);
            return result;
        }
        
        if(root -> left != nullptr){
            string tmp1;
            tmp1 += int2str(root -> val);
            execTraverl(root -> left, result, tmp1);
        }
        
        if(root -> right != nullptr){
            string tmp2;
            tmp2 += int2str(root -> val);
            execTraverl(root -> right, result, tmp2);
        }
        
        return result;
    }
};


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

Binary Tree Paths

标签:c++   代码      

原文地址:http://blog.csdn.net/ny_mg/article/details/48086379

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