/**
* 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 dfs(TreeNode* root, string &cur, vector<string> &res) {
if (!root) return;
string temp = cur;
if ((!root->left) && (!root->right)) {
res.push_back(cur);
cur = temp;
return;
}
if (root->left) {
cur += "->";
cur += to_string(root->left->val);
dfs(root->left, cur, res);
cur = temp;
}
if (root->right) {
cur += "->";
cur += to_string(root->right->val);
dfs(root->right, cur, res);
cur = temp;
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (!root) return res;
string cur;
cur += static_cast<ostringstream*>( &(ostringstream() << root->val) )->str();
dfs(root, cur, res);
return res;
}
};Binary Tree Paths
最新推荐文章于 2024-11-03 20:00:49 发布
本文介绍了一种使用递归方法遍历二叉树并收集所有从根节点到叶子节点路径的方法,通过定义一个二叉树节点结构,并实现了一个Solution类,包含dfs和binaryTreePaths两个方法来实现此功能。
405

被折叠的 条评论
为什么被折叠?



