层序遍历,队列
-------------------------------------------------------------------------------------
时间限制:1秒 空间限制:32768K 热度指数:314273
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/* 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) { vector<int> que; queue<TreeNode*>Q; TreeNode* start; if(root == NULL) return que; Q.push(root); while(!Q.empty()) { start=Q.front(); que.push_back(start->val); if(start->left != NULL) Q.push(start->left); if(start->right != NULL) Q.push(start->right); Q.pop(); } return que; } };