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] ]
给定一棵二叉树,对其进行层次遍历。使用一个队列,加入一个NULL标记层次,每次从队首取出一个节点,然后存入结果,并把他的孩子加入队尾,直到队列为空。
代码如下:
1 /** 2 * Definition for binary tree 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 // Note: The Solution object is instantiated only once and is reused by each test case. 14 queue<TreeNode*> q; 15 q.push(NULL); 16 vector<vector<int>> result; 17 vector<int> temp; 18 if(root == NULL)return result; 19 else 20 { 21 q.push(root); 22 while(q.size()!=1) 23 { 24 while(q.front()!=NULL) 25 { 26 temp.push_back(q.front()->val); 27 if(q.front()->left!=NULL) q.push(q.front()->left); 28 if(q.front()->right!=NULL) q.push(q.front()->right); 29 q.pop(); 30 } 31 if(q.front()==NULL) 32 { 33 q.pop(); 34 q.push(NULL); 35 } 36 if(temp.size()!=0) result.push_back(temp); 37 temp.clear(); 38 } 39 } 40 return result; 41 } 42 };