257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
/**
* 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(vector<string> &v, TreeNode *node, string s) {
if(node->left == NULL && node->right == NULL) {
v.push_back(s);
return ;
}
if(node->left != NULL) {
dfs(v, node->left, s + "->" + to_string(node->left->val));
}
if(node->right != NULL) {
dfs(v, node->right, s + "->" + to_string(node->right->val));
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> v;
if(root == NULL) {
return v;
}
dfs(v, root, to_string(root->val));
return v;
}
};
本文介绍了一种算法,用于找出二叉树中从根节点到叶子节点的所有路径。通过深度优先搜索(DFS)遍历树结构,并将路径字符串拼接起来实现。示例展示了对于特定二叉树输入,如何获取所有可能的路径。
418

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



