
题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:
使用队列
时间复杂度: $O(n)$, 空间复杂度: $O(n)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > vec; queue<TreeNode *> q; if(!pRoot) return vec; q.push(pRoot); while(!q.empty()) { int qsize = q.size(); vector<int> temp; for(int i = 0; i < qsize;i++) { TreeNode* t = q.front(); if(t -> left)q.pu.sh(t->left); if(t -> right)q.push(t->right); temp.push_back(t -> val); q.pop(); } vec.push_back(temp); } return vec; } };
|
近期评论