Description:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Note:
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] ]
Solution:
Analysis and Thinking:
這是一道明顯的層序遍歷二叉樹的題目,遵循一般的思路即:如果隊列不空,將樹的根入隊列餓,再進行循環
Steps:
1.初始化隊列,輸入樹
2.將樹的根節點入隊,並進行循環
3.當隊列不空,將隊首部的元素出隊,並判斷其是否有左、右子樹,分別將其子樹入隊
4.遍歷完成,返回結果
Codes:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector< vector<int> > levelOrder(TreeNode* root) {
vector< vector<int> > result;
if(!root)
return res;
queue<TreeNode *> tempQue;
tempQue.push(root);
while(!tempQue.empty()){ vector<int> tempLevel; int size = tempQue.size(); for(int i = 0; i < size; i ++){ TreeNode *t = tempQue.front(); tempQue.pop();
tempLevel.push_back(t -> val); if(t -> left) tempQue.push(t -> left); if(t -> right) tempQue.push(t -> right); } result.push_back(everylevel); } return result; } };
Results: