cpp-algo-cases/chapter_backtracking/preorder_traversal_i_compac...

40 lines
777 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: preorder_traversal_i_compact.cpp
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
vector<TreeNode *> res;
/* ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ */
void preOrder(TreeNode *root) {
if (root == nullptr) {
return;
}
if (root->val == 7) {
// <20><>¼<EFBFBD><C2BC>
res.push_back(root);
}
preOrder(root->left);
preOrder(root->right);
}
/* 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>ֵΪ 7 <20>Ľڵ<C4BD>" << endl;
vector<int> vals;
for (TreeNode *node : res) {
vals.push_back(node->val);
}
printVector(vals);
}