剑指offer系列16:从上往下打印二叉树

层次打印二叉树,竟然用一个队列就很简单的完成了;

首先将树的根结点放进队列,然后出的时候是先进先出。并且出去的时候判断这个节点的左右节点是否有节点,如果有就插入队列的后面。

 1 #include<iostream>
 2 #include<vector>
 3 #include<stack>
 4 using namespace std;
 5 struct TreeNode {
 6 int val;
 7 struct TreeNode *left;
 8 struct TreeNode *right;
 9 /*
10 TreeNode(int x) :
11 val(x), left(NULL), right(NULL) {
12 }
13 */
14 };
15 class Solution {
16 public:
17     vector<int> PrintFromTopToBottom(TreeNode* root) {
18         vector<int> re;
19         
20         if (root == NULL)
21             return re;
22 
23         std::deque<TreeNode*> de;
24         de.push_back(root);//先把根结点放进队列中
25         while(de.size())
26         {
27             TreeNode* pnode = de.front();//找到队列的头结点
28             re.push_back(pnode->val);
29             if (pnode->left)//判断该结点后是否有结点,如果有结点放到队列后面
30             {
31                 de.push_back(pnode->left);
32             }
33             if (pnode->right)
34             {
35                 de.push_back(pnode->right);
36             }
37             de.pop_front();
38         }
39         return re;
40 
41     }
42 };
43 int main()
44 {
45     Solution so;
46     vector<int> aa;
47     TreeNode list[3];
48     list[0].val = 1;
49     list[0].left = &list[1];
50     list[0].right = &list[2];
51     list[1].val = 3;
52     list[1].left =NULL;
53     list[1].right = NULL;
54     list[2].val = 2;
55     list[2].left = NULL;
56     list[2].right = NULL;
57     aa = so.PrintFromTopToBottom(list);
58     for (int i = 0; i < aa.size(); i++)
59     {
60         cout << aa[i] << endl;
61     }
62     return 0;
63 }

有一个小问题,37行的弹出操作也可以写在28之后,也就是说已经弹出队列的第一个结点,之后还可以在存好的指针中找到它的左右指针变量,删除了还能找到吗。

原文地址:https://www.cnblogs.com/neverland0718/p/11017646.html