leetcode-257-Binary Tree Paths

来源:互联网 发布:化合物数据库 编辑:程序博客网 时间:2024/06/05 14:10

问题

题目:[leetcode-257]

思路

深度优先即可。

代码

/** * 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:    vector<string> binaryTreePaths(TreeNode* root) {        std::vector<std::string> ret;        if(!root) return ret;        std::string s;        dfs(root, s, ret);        return ret;    }private:    void dfs( TreeNode* root, std::string str, std::vector<std::string>& ret  ){        if(!root) return;        if(!(root->left)&&!(root->right)){            str += int2Str(root->val);            ret.push_back(str);        }        else{            str += int2Str(root->val);            str += "->";            dfs(root->left, str, ret);            dfs(root->right, str, ret);        }        str.pop_back();    }    std::string int2Str(int val){        std::stringstream ss;        ss << val;        return ss.str();    }};
0 0