cpp-algo-cases/chapter_tree/binary_tree_dfs.cpp

70 lines
1.4 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: binary_tree_dfs.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
// <20><>ʼ<EFBFBD><CABC><EFBFBD>б<EFBFBD><D0B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڴ洢<DAB4><E6B4A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
vector<int> vec;
/* ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȼ<EFBFBD><C8BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD> -> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> -> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
vec.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȼ<EFBFBD><C8BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> -> <20><><EFBFBD>ڵ<EFBFBD> -> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
inOrder(root->left);
vec.push_back(root->val);
inOrder(root->right);
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȼ<EFBFBD><C8BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> -> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> -> <20><><EFBFBD>ڵ<EFBFBD>
postOrder(root->left);
postOrder(root->right);
vec.push_back(root->val);
}
/* Driver Code */
int main() {
/* <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD><EFBFBD><EFBFBD>ɶ<EFBFBD><C9B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ĺ<EFBFBD><C4BA><EFBFBD>
TreeNode *root = vectorToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
cout << endl << "<EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\n" << endl;
printTree(root);
/* ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
vec.clear();
preOrder(root);
cout << endl << "ǰ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľڵ<EFBFBD><EFBFBD><EFBFBD>ӡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
printVector(vec);
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
vec.clear();
inOrder(root);
cout << endl << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľڵ<EFBFBD><EFBFBD><EFBFBD>ӡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
printVector(vec);
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
vec.clear();
postOrder(root);
cout << endl << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľڵ<EFBFBD><EFBFBD><EFBFBD>ӡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
printVector(vec);
return 0;
}