输出二叉树从每个叶子结点到根结点的路径(经历的结点)C++
时间: 2023-12-29 17:04:57 浏览: 137
以下是输出二叉树从每个叶子节点到根节点的路径的C++代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void findPaths(TreeNode* root, vector<int>& path, vector<vector<int>>& paths) {
if (root == NULL) {
return;
}
// 将当前结点值加入路径
path.push_back(root->val);
// 如果当前结点是叶子结点,则将路径加入结果集
if (root->left == NULL && root->right == NULL) {
paths.push_back(path);
}
// 递归遍历左右子树
findPaths(root->left, path, paths);
findPaths(root->right, path, paths);
// 回溯,将当前结点从路径中删除
path.pop_back();
}
vector<vector<int>> leafPaths(TreeNode* root) {
vector<vector<int>> paths;
vector<int> path;
findPaths(root, path, paths);
return paths;
}
int main() {
/* 测试样例:
1
/ \
2 3
/ \
4 5
*/
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
vector<vector<int>> paths = leafPaths(root);
for (auto path : paths) {
for (auto node : path) {
cout << node << " ";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
4 2 1
5 2 1
3 1
```
阅读全文