You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.1 KiB
48 lines
1.1 KiB
2 years ago
|
/**
|
||
2 years ago
|
* File: preorder_traversal_iii_compact.cpp
|
||
2 years ago
|
* Created Time: 2023-04-16
|
||
|
* Author: Krahets (krahets@163.com)
|
||
|
*/
|
||
|
|
||
|
#include "../include/include.hpp"
|
||
|
|
||
|
vector<TreeNode *> path;
|
||
|
vector<vector<TreeNode *>> res;
|
||
|
|
||
2 years ago
|
/* 前序遍历:例题三 */
|
||
2 years ago
|
static void preOrder(TreeNode *root) {
|
||
2 years ago
|
// 剪枝
|
||
2 years ago
|
if (root == nullptr || root->val == 3) {
|
||
|
return;
|
||
|
}
|
||
|
// 尝试
|
||
|
path.push_back(root);
|
||
|
if (root->val == 7) {
|
||
|
// 记录解
|
||
|
res.push_back(path);
|
||
|
}
|
||
|
preOrder(root->left);
|
||
|
preOrder(root->right);
|
||
|
// 回退
|
||
|
path.pop_back();
|
||
|
}
|
||
|
|
||
2 years ago
|
/* Driver Code */
|
||
2 years ago
|
int main() {
|
||
|
TreeNode *root = vecToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
|
||
|
cout << "\n初始化二叉树" << endl;
|
||
|
printTree(root);
|
||
|
|
||
|
// 前序遍历
|
||
|
preOrder(root);
|
||
|
|
||
|
cout << "\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点" << endl;
|
||
|
for (vector<TreeNode *> &path : res) {
|
||
|
vector<int> vals;
|
||
|
for (TreeNode *node : path) {
|
||
|
vals.push_back(node->val);
|
||
|
}
|
||
|
printVector(vals);
|
||
|
}
|
||
|
}
|