cpp-algo-cases/chapter_backtracking/preorder_traversal_ii_compa...

47 lines
960 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: preorder_traversal_ii_compact.cpp
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
vector<TreeNode *> path;
vector<vector<TreeNode *>> res;
/* ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void preOrder(TreeNode *root) {
if (root == nullptr) {
return;
}
// <20><><EFBFBD><EFBFBD>
path.push_back(root);
if (root->val == 7) {
// <20><>¼<EFBFBD><C2BC>
res.push_back(path);
}
preOrder(root->left);
preOrder(root->right);
// <20><><EFBFBD><EFBFBD>
path.pop_back();
}
/* Driver Code */
int main() {
TreeNode *root = vectorToTree(vector<int>{1, 7, 3, 4, 5, 6, 7});
cout << "\n<EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>" << endl;
printTree(root);
// ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
preOrder(root);
cout << "\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>и<EFBFBD><EFBFBD>ڵ㵽<EFBFBD>ڵ<EFBFBD> 7 <20><>·<EFBFBD><C2B7>" << endl;
for (vector<TreeNode *> &path : res) {
vector<int> vals;
for (TreeNode *node : path) {
vals.push_back(node->val);
}
printVector(vals);
}
}