1. 描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
2. 例子
示例 1:
给定二叉树: [3,9,20,null,null,15,7],
[3,9,20,15,7]
3. 提示
4. 题解
n 是 i_root 中的节点数目
时间复杂度: O(n)
空间复杂度: O(n)
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
| class Solution
{
public:
// vector<int> levelOrder(TreeNode* root)
vector<int> levelOrder(TreeNode *i_root)
{
if(!i_root) return vector<int>{};
queue<TreeNode *> currentLayer{{i_root}};
queue<TreeNode *> nextLayer;
vector<int> prints;
while(!currentLayer.empty() || !nextLayer.empty())
{
if(currentLayer.empty())
{
swap(currentLayer, nextLayer);
}
else
{
auto node = currentLayer.front();
currentLayer.pop();
prints.push_back(node->val);
if(node->left) nextLayer.push(node->left);
if(node->right) nextLayer.push(node->right);
}
}
return prints;
}
};
|