题目链接:https://leetcode-cn.com/problems/binary-tree-paths/
题目描述:
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
解题:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void getPaths(TreeNode* node, string path, vector<string> &vec)
{
if(node != nullptr)
{
path += to_string(node->val); //只有节点不空,加入路径中
if(node->left == nullptr && node->right == nullptr) //叶子节点,表明该节点为路径终点
{
vec.push_back(path);
}else{ //还有孩子节点,继续向下查找叶子节点
path += "->";
getPaths(node->left, path, vec);
getPaths(node->right, path, vec);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path = "";
if(root == nullptr)
return result;
getPaths(root, path, result);
return result;
}
};