给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解题思路
用两个队列,一个存放树节点node_queue,一个存放到当前节点的路径path_queue
每次取出两个队列的队首,判断当前节点是否为叶子节点
如果是叶子节点(没有左右孩子),说明这一条路径已经完成,直接将path加进res就行
如果不是叶子节点,那么分以下两种情况:
1.左孩子不为空,那么将左孩子加入到node_queue队列中,并更新路径path到path_queue中
2.右孩子不为空,那么将右孩子加入到node_queue队列中,并更新路径path到path_queue中
最后返回res
这里除了根节点,其他节点都是在父节点时就添加进了路径中,所以当遇到叶子节点时也就不用再添加叶子节点的值到path,直接将path添加到res即可
/**两个队列来做
* 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) {
if(root == nullptr) return {};
vector<string> res; //res存放结果:路径
queue<TreeNode*> node_que; //存放节点
queue<string> path_que; //存放当前路径
node_que.push(root);
path_que.push(to_string(root->val));
while(!node_que.empty()){
TreeNode *node = node_que.front(); node_que.pop();
string path = path_que.front(); path_que.pop();
if(node->left == nullptr && node->right == nullptr){
//当节点没有左右孩子,说明这条路径到底了,将path加进结果
res.push_back(path);
}else{ //注意两个都是if,以及里面的条件
if(node->left != nullptr){
node_que.push(node->left);
path_que.push(path + "->"+ to_string(node->left->val));
}
if(node->right != nullptr){
node_que.push(node->right);
path_que.push(path + "->"+ to_string(node->right->val));
}
}
}
return res;
}
};
/**递归
* 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* node, string path, vector<string> &paths)
{
if(node == nullptr) return;
if(node->left == nullptr && node->right == nullptr){
paths.push_back(path + to_string(node->val));
return;
}else{
if(node->left != nullptr){
dfs(node->left, path + to_string(node->val) + "->" , paths);
}
if(node->right != nullptr){
dfs(node->right, path + to_string(node->val) + "->", paths);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
dfs(root, "", paths);
return paths;
}
};