Leetcode 102. Binary Tree Level Order Traversal
题目描述
Given the root
of a binary tree, return the level order
traversal of its nodes' values. (i.e., from left to right, level by
level).
Example 1:

Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
-
The number of nodes in the tree is in the range
[0, 2000]
. -
-1000 <= Node.val <= 1000
解答
就是BFS,每一层分割一下。
注意2D的vector要新增一行,push的部分是个1D的vector,而new出来的是个指针,需要再指向一下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
int layer=0;
deque<TreeNode*> *q=new deque<TreeNode*> ,*q2=new deque<TreeNode*>,*qtmp;
if (root==nullptr)
return ans;
(*q).push_back(root);
while(q->size()!=0||q2->size()!=0){
ans.push_back(*new vector<int>);
while((*q).size()){
ans[layer].push_back(q->front()->val);
if (q->front()->left!=nullptr)
q2->push_back(q->front()->left);
if (q->front()->right!=nullptr)
q2->push_back(q->front()->right);
q->pop_front();
}
qtmp=q;
q=q2;
q2=qtmp;
layer++;
}
return ans;
}
};
Complexity
- Time: \(O(n)\)
- Space: \(O(n)\)