二叉树层次遍历

 1 #include <iostream>
 2 #include <vector>
 3 #include <queue>
 4 using namespace std;
 5 
 6 void Print(const vector<int> &v)
 7 {
 8     for(auto it:v)
 9     {
10         cout<<it<<" ";
11     }
12     cout<<endl;
13 }
14 struct Treenode//定义树的节点 
15 {
16     int val;
17     Treenode* left;
18     Treenode* right;
19     Treenode(int _val):val(_val),left(nullptr),right(nullptr){}
20 };
21 //[in] 树的根节点
22 //[out] 一维vector的层次遍历结果 
23 //层次遍历关键在于queue的使用 
24 vector<int> cenci(Treenode* root)
25 {
26     vector<int> result;
27     queue<Treenode*> que;
28     //if(root==nullptr) return nullptr;
29     que.push(root);
30     while(!que.empty())
31     {
32         Treenode* node=que.front();
33         que.pop();
34         if(node->left) que.push(node->left);
35         if(node->right) que.push(node->right);
36         result.push_back(node->val);
37     }
38     return result;
39 }
40 //[in]树的根节点 
41 //[out]二维vector的层次遍历结果 
42 vector<vector<int>> bianli(Treenode* root)
43 {
44     vector<vector<int>> result;//返回结果 
45     queue<Treenode*> que;
46     que.push(root);
47     
48     while(!que.empty())
49     {
50         vector<int> v;
51         size_t size=que.size();//当前行节点个数 
52         for(size_t i=0;i<size;++i)//当前行节点的所有子节点加入队列 
53         {
54             Treenode* node=que.front();
55             que.pop();
56             if(node->left) que.push(node->left); 
57             if(node->right) que.push(node->right);
58             v.push_back(node->val);
59         }
60         result.push_back(v);
61     }
62     return result; 
63     
64 }
65 int main(int argc, char *argv[])
66 {
67 
68     Treenode *t1=new Treenode(2);
69     Treenode *t2=new Treenode(3);
70     Treenode *t3=new Treenode(4);
71     Treenode *t4=new Treenode(5);
72     t1->left=t2;
73     t1->right=t3;
74     t2->left=t4;
75     //vector<int> result= cenci(t1);
76     //Print(result);
77     vector<vector<int>> result=bianli(t1);
78     for(auto it:result)//遍历输出结果 
79     {
80         for(auto it2:it)
81         {
82             cout<<it2<<" ";
83         }
84     }
85     return 0;
86 }

 

posted @ 2022-01-02 10:21  菠萝超级酸  阅读(23)  评论(0编辑  收藏  举报