2023-04-16 16:34:52 +08:00
|
|
|
/**
|
2023-04-22 01:38:53 +08:00
|
|
|
* File: preorder_traversal_ii_compact.cpp
|
2023-04-16 16:34:52 +08:00
|
|
|
* Created Time: 2023-04-16
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
*/
|
|
|
|
|
2023-04-24 04:11:18 +08:00
|
|
|
#include "../utils/common.hpp"
|
2023-04-16 16:34:52 +08:00
|
|
|
|
|
|
|
vector<TreeNode *> path;
|
|
|
|
vector<vector<TreeNode *>> res;
|
|
|
|
|
2023-04-22 01:38:53 +08:00
|
|
|
/* 前序遍历:例题二 */
|
2023-04-16 16:34:52 +08:00
|
|
|
static void preOrder(TreeNode *root) {
|
|
|
|
if (root == nullptr) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// 尝试
|
|
|
|
path.push_back(root);
|
|
|
|
if (root->val == 7) {
|
|
|
|
// 记录解
|
|
|
|
res.push_back(path);
|
|
|
|
}
|
|
|
|
preOrder(root->left);
|
|
|
|
preOrder(root->right);
|
|
|
|
// 回退
|
|
|
|
path.pop_back();
|
|
|
|
}
|
|
|
|
|
2023-04-17 21:13:15 +08:00
|
|
|
/* Driver Code */
|
2023-04-16 16:34:52 +08:00
|
|
|
int main() {
|
|
|
|
TreeNode *root = vecToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
|
|
|
cout << "\n初始化二叉树" << endl;
|
|
|
|
printTree(root);
|
|
|
|
|
|
|
|
// 前序遍历
|
|
|
|
preOrder(root);
|
|
|
|
|
|
|
|
cout << "\n输出所有根节点到节点 7 的路径" << endl;
|
|
|
|
for (vector<TreeNode *> &path : res) {
|
|
|
|
vector<int> vals;
|
|
|
|
for (TreeNode *node : path) {
|
|
|
|
vals.push_back(node->val);
|
|
|
|
}
|
|
|
|
printVector(vals);
|
|
|
|
}
|
|
|
|
}
|