剑指offer之【从上往下打印二叉树】

题目:

  从上往下打印二叉树

链接:

  https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:

  从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路:

  建立一个序列:对当前点的左右子节点进行扫描,非空则压入序列,然后对当且节点输入并弹出(只要序列不为空则一直进行此步骤)

代码:

  

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     vector<int> PrintFromTopToBottom(TreeNode* root){
13         if(root == nullptr)
14               return res;
15         stk.push(root);
16         while(!stk.empty()){
17             TreeNode* temp = stk.front();
18             if(temp->left != nullptr){
19                 stk.push(temp->left);
20             }
21             if(temp->right != nullptr){
22                 stk.push(temp->right);
23             }
24             res.push_back(temp->val);
25             stk.pop();
26         }
27         return res;
28     }
29 private:
30     vector<int> res;
31     queue<TreeNode*> stk;
32 };
原文地址:https://www.cnblogs.com/wangshujing/p/6936794.html