43 lines
1.1 KiB
C++
43 lines
1.1 KiB
C++
|
/**
|
|||
|
* File: binary_tree_bfs.cpp
|
|||
|
* Created Time: 2022-11-25
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
vector<int> levelOrder(TreeNode *root) {
|
|||
|
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD>У<EFBFBD><D0A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
|
|||
|
queue<TreeNode *> queue;
|
|||
|
queue.push(root);
|
|||
|
// <20><>ʼ<EFBFBD><CABC>һ<EFBFBD><D2BB><EFBFBD>б<EFBFBD><D0B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڱ<EFBFBD><DAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
vector<int> vec;
|
|||
|
while (!queue.empty()) {
|
|||
|
TreeNode *node = queue.front();
|
|||
|
queue.pop(); // <20><><EFBFBD>г<EFBFBD><D0B3><EFBFBD>
|
|||
|
vec.push_back(node->val); // <20><><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>ֵ
|
|||
|
if (node->left != nullptr)
|
|||
|
queue.push(node->left); // <20><><EFBFBD>ӽڵ<D3BD><DAB5><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
if (node->right != nullptr)
|
|||
|
queue.push(node->right); // <20><><EFBFBD>ӽڵ<D3BD><DAB5><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
}
|
|||
|
return vec;
|
|||
|
}
|
|||
|
|
|||
|
/* 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);
|
|||
|
|
|||
|
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
vector<int> vec = levelOrder(root);
|
|||
|
cout << endl << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľڵ<EFBFBD><EFBFBD><EFBFBD>ӡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> = ";
|
|||
|
printVector(vec);
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|