Leetcode 102. Binary Tree Level Order Traversal
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.
OJ's Binary Tree Serialization:
View Code
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
分析:二叉树的层序遍历,使用广度优先搜索,建立一个队列q。
每次将队首temp结点出队列的同时,将temp的左孩子和右孩子入队
用size标记入队后的队列长度
row数组始终为当前层的遍历结果,然后用while(size–)语句保证每一次保存入row的只有一层。
每一次一层遍历完成后,将该row的结果存入二维数组v。
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<int> row; 14 vector<vector<int>> v; 15 queue<TreeNode *> q; 16 if(root == NULL) 17 return v; 18 q.push(root); 19 TreeNode *temp; 20 while(!q.empty()) { 21 int size = q.size(); 22 while(size--) { 23 temp = q.front(); 24 q.pop(); 25 row.push_back(temp->val); 26 if(temp->left != NULL) { 27 q.push(temp->left); 28 } 29 if(temp->right != NULL) { 30 q.push(temp->right); 31 } 32 } 33 v.push_back(row); 34 row.clear(); 35 } 36 return v; 37 } 38 };
越努力,越幸运