Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
/**
* 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 {
private:
vector<string> res{};
void search(TreeNode* root, string path) {
if(root == nullptr) {
return ;
}
path += path == "" ? to_string(root->val) : "->" + to_string(root->val);
if(root->left == nullptr && root->right == nullptr) {
res.push_back(path);
return ;
}
if(root->left) {
search(root->left, path);
}
if(root->right) {
search(root->right, path);
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
search(root, "");
return res;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有