标签:printf push question pop return ret tree turn cto
题目:从上往下打印二叉树
要求:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
* 注意: 此题只是要求返回一维数组,若需要返回二维数组(即按照层序遍历的顺序,每一层的节点存放到一个一维数组,最后多层组合为二维数组),请点击这里
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { } };
解题代码:
1 class Solution { 2 public: 3 vector<int> PrintFromTopToBottom(TreeNode* root) { 4 vector<int> res; 5 if(root == nullptr) 6 return res; 7 8 TreeNode* p = root; 9 queue<TreeNode*> q; 10 q.push(root); 11 12 while(!q.empty()){ 13 TreeNode* temp = q.front(); 14 res.push_back(temp->val); 15 q.pop(); 16 17 if(temp->left != nullptr) 18 q.push(temp->left); 19 if(temp->right) 20 q.push(temp->right); 21 } 22 return res; 23 } 24 };
标签:printf push question pop return ret tree turn cto
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9873669.html