标签:
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ 9 20
/ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
层次遍历二叉树,并要求将每一层的数放在二维数组的同一行中。
思路:采用两个队列,队列1存放上一层结点,队列1中的结点一次出队并在队列2存放下一层结点,另外用一个数组记录队列1中结点的值,这些值就属于一层。
将数组中的值放入二维数组相应的行,并清空数组。队列2中的结点出队并一次放入队列1中。
代码如下:
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 vector<vector<int>> lorder; 14 if(root == NULL) 15 { 16 return lorder; 17 } 18 queue<TreeNode*> q; 19 q.push(root); 20 vector<int> level_tmp2; 21 while(!q.empty()) 22 { 23 level_tmp2.clear(); 24 queue<TreeNode*> level_tmp1; 25 TreeNode* node = q.front(); 26 int size = q.size(); 27 28 for(int i = 0; i < size; i++) 29 { 30 TreeNode* node = q.front(); 31 q.pop(); 32 if(node->left) 33 { 34 level_tmp1.push(node->left); 35 } 36 if(node->right) 37 { 38 level_tmp1.push(node->right); 39 } 40 level_tmp2.push_back(node->val); 41 } 42 while(!level_tmp1.empty()) 43 { 44 q.push(level_tmp1.front()); 45 level_tmp1.pop(); 46 } 47 lorder.push_back(level_tmp2); 48 } 49 return lorder; 50 } 51 };
标签:
原文地址:http://www.cnblogs.com/shellfishsplace/p/5867752.html