用隊(duì)列去進(jìn)行實(shí)現(xiàn)彩届,先把根節(jié)點(diǎn)壓入隊(duì)列中抗俄,然后開(kāi)始循環(huán)梁棠,每次循環(huán)時(shí)針對(duì)隊(duì)首結(jié)點(diǎn)靠闭,將其左節(jié)點(diǎn)和有節(jié)點(diǎn)壓入隊(duì)列,然后隊(duì)首結(jié)點(diǎn)就彈出塞琼,這樣就可以實(shí)現(xiàn)對(duì)一個(gè)二叉樹(shù)進(jìn)行層序的遍歷了菠净。
#include <iostream>
using namespace std;
#include <string>
#include<queue>
struct TreeNode
{
int val;
TreeNode * left;
TreeNode * right;
TreeNode(int x): val(x),left(nullptr),right(nullptr){}
};
int main() {
queue<TreeNode*> res;
TreeNode *head = new TreeNode(1);
TreeNode *p = head;
head->left = new TreeNode(2);
head->right = new TreeNode(3);
head->left->left = new TreeNode(4);
head->left->right = new TreeNode(5);
head->right->left = new TreeNode(6);
head->right->right = new TreeNode(7);
vector<int> to_pr;
res.push(head);
while (!res.empty()) {
if (res.front()->left) {
res.push(res.front()->left);
}
if (res.front()->right) {
res.push(res.front()->right);
}
to_pr.push_back(res.front()->val);
res.pop();
}
for (int i = 0; i < to_pr.size(); i++) {
if (i < to_pr.size() - 1) cout << to_pr[i] << "->";
else cout << to_pr[i];
}
system("pause");
return 0;
}