给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
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:
void find_path(TreeNode* node,string path,vector<string>& vec)
{
if(node)
{
path+=to_string(node->val);
if(node->left==nullptr&&node->right==nullptr)
{
vec.push_back(path);//找到根节点,路径添加入数组
}
else
{
path+="->";
find_path(node->left,path,vec);
find_path(node->right,path,vec);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
find_path(root,"",vec);
return vec;
}
};
BFS
两个队列相互对应,每个节点对应路径队列里的路径,注意保证两者同出同进。
/**
* 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> paths;
if(!root)
return paths;
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();
string path=path_que.front();
node_que.pop();
path_que.pop();
if(node->left==nullptr&&node->right==nullptr)
paths.push_back(path);
else
{
if(node->left)
{
node_que.push(node->left);
path_que.push(path+"->"+to_string(node->left->val));
}
if(node->right)
{
node_que.push(node->right);
path_que.push(path+"->"+to_string(node->right->val));
}
}
}
return paths;
}
};
stack实现DFS
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt;// 保存树的遍历节点
stack<string> pathSt; // 保存遍历路径的节点
vector<string> result; // 保存最终路径集合
if (root == NULL) return result;
treeSt.push(root);
pathSt.push(to_string(root->val));
while (!treeSt.empty()) {
TreeNode* node = treeSt.top(); treeSt.pop(); // 取出节点 中
string path = pathSt.top();pathSt.pop(); // 取出该节点对应的路径
if (node->left == NULL && node->right == NULL) { // 遇到叶子节点
result.push_back(path);
}
if (node->right) { // 右
treeSt.push(node->right);
pathSt.push(path + "->" + to_string(node->right->val));
}
if (node->left) { // 左
treeSt.push(node->left);
pathSt.push(path + "->" + to_string(node->left->val));
}
}
return result;
}
};