题意:
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解题思路:
就DFS模板吧,
/**
* 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) {
vector<string> ans;
if(root == NULL) {
return ans;
}
dfs(root, "", ans);
return ans;
}
void dfs(TreeNode* root, string path, vector<string>& v) {
path += to_string(root->val); // 当前数字插入路径
if(root->left == NULL && root->right == NULL) {
v.push_back(path); // 左右孩子都为空,为子叶子节点
}
path += "->"; // 如果还有子叶子节点
if(root->left != NULL) {
dfs(root->left, path, v); // 向左
}
if(root->right != NULL) {
dfs(root->right, path, v); // 向右
}
}
};