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] ]
思路:使用队列,等到这一层遍历结束再输出
void LevelOrder(BinTree* root) { if(root == NULL) return ; deque<BinTree*> de; int num; int curnum=0; int i; BinTree* node; de.push_back(root); vector<int> vec; num =1; while(!de.empty()) { node = de.front(); de.pop_front(); num--; vec.push_back(node->value); if(node->left != NULL) { de.push_back(node->left); curnum++; } if(node->right !=NULL) { de.push_back(node->right); curnum++; } if(num ==0) { num =curnum; curnum =0; for(i=0;i<vec.size();i++) cout<<vec[i]<<" "; cout<<endl; vec.clear(); } } }
Binary Tree Level Order Traversal--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44886293