生成打印二叉树从根结点到叶子结点的所有路径的c++程序
时间: 2023-12-29 08:05:46 浏览: 93
以下是基于递归的C++程序,可以生成打印二叉树从根结点到叶子结点的所有路径:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 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) return res;
dfs(root, "", res);
return res;
}
private:
void dfs(TreeNode* node, string path, vector<string>& res) {
if (!node->left && !node->right) {
res.push_back(path + to_string(node->val));
return;
}
if (node->left) dfs(node->left, path + to_string(node->val) + "->", res);
if (node->right) dfs(node->right, path + to_string(node->val) + "->", res);
}
};
int main() {
// create a test binary tree
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->right = new TreeNode(5);
Solution sol;
vector<string> res = sol.binaryTreePaths(root);
for (auto path : res) {
cout << path << endl;
}
return 0;
}
```
程序中使用了一个`dfs`函数来遍历整个二叉树并记录路径,同时使用了一个`res`向量来存储所有路径。当遇到叶子节点时,将路径添加到`res`向量中。最后,程序输出所有路径。
阅读全文