面试题32 - II. 从上到下打印二叉树 II
题目:
解答:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) 13 { 14 vector<vector<int>> res; 15 16 if (NULL == root) 17 { 18 return res; 19 } 20 21 queue<TreeNode*> q; 22 q.push(root); 23 int count = 1; 24 int level = 0; 25 26 vector<int> tmp; 27 28 while (!q.empty()) 29 { 30 tmp.clear(); 31 level = 0; 32 33 for (int i = 0; i < count; i++) 34 { 35 TreeNode *root = q.front(); 36 q.pop(); 37 tmp.push_back(root->val); 38 39 if (root->left) 40 { 41 q.push(root->left); 42 level++; 43 } 44 if (root->right) 45 { 46 q.push(root->right); 47 level++; 48 } 49 } 50 51 count = level; 52 53 res.push_back(tmp); 54 } 55 56 return res; 57 } 58 };