Article Directory
Subject: 257. All paths of a binary tree
Given a binary tree, return all paths from the root node to the leaf nodes.
Explanation: A leaf node refers to a node without child nodes.
Example:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-tree-paths
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Basic idea: 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> res;
vector<string> binaryTreePaths(TreeNode* root) {
if(root == NULL)
return res;
dfs(root, "");
return res;
}
void dfs(TreeNode * root, string cur){
string temp = to_string(root->val);
if(cur == ""){
cur += temp;
}
else{
cur += "->" + temp;
}
if(root->left == NULL && root->right == NULL){
//遇到根节点存放结果
res.push_back(cur);
return;
}
if(root->left){
dfs(root->left, cur);
}
if(root->right){
dfs(root->right, cur);
}
}
};
Basic idea 2: bfs
You can also use bfs
- Maintain two queues, one queue is used to store the current node, and one queue is used to store the path formed by the node.
- Every time a node is ejected from the queue, a path is also ejected at the same time,
- If the current node has a left child, the left child is connected to the current path and the path is enqueued; similarly, if the current node has children, the right child of the current node is also added to the current path and the path is enqueued.
/**
* 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> res;
if(root == NULL)
return res;
queue<TreeNode*> q;
queue<string> path;
q.push(root);
path.push(to_string(root->val));
while(!q.empty()){
auto temp_n = q.front();
auto temp_p = path.front();
q.pop();
path.pop();
if(temp_n->left == NULL && temp_n->right == NULL){
res.push_back(temp_p);
}
if(temp_n->left){
q.push(temp_n->left);
path.push(temp_p + "->" + to_string(temp_n->left->val));
}
if(temp_n->right){
q.push(temp_n->right);
path.push(temp_p + "->" + to_string(temp_n->right->val));
}
}
return res;
}
};