标签:
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
[Solution]
二叉树层次遍历,即广度遍历,使用队列做辅助。
1 vector<vector<int> > levelOrder(TreeNode *root) 2 { 3 vector<vector<int> > result; 4 vector<int> line; 5 queue<TreeNode *> qtree; 6 TreeNode *visit = root; 7 int current_level_size = 1, next_level_size = 0; 8 9 if (visit != NULL) 10 qtree.push(visit); 11 while (!qtree.empty()) 12 { 13 visit = qtree.front(); 14 qtree.pop(); 15 current_level_size--; 16 line.push_back(visit->val); 17 18 if (visit->left != NULL) 19 { 20 qtree.push(visit->left); 21 next_level_size++; 22 } 23 if (visit->right != NULL) 24 { 25 qtree.push(visit->right); 26 next_level_size++; 27 } 28 if (current_level_size == 0) // all this level nodes are visited. 29 { 30 result.push_back(line); 31 line.clear(); 32 current_level_size = next_level_size; 33 next_level_size = 0; 34 } 35 } 36 37 return result; 38 }
leetcode 102. Binary Tree Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4295385.html