剑指32:从上到下打印二叉树

传送门

nowcoder
leetcode

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

C++ 代码 - nowcoder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
层次遍历,使用一个队列
*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
if (root == nullptr) return vector<int>{};

vector<int> res;
queue<TreeNode*> q;
q.push(root);
TreeNode* node = nullptr;
while (!q.empty()) {
node = q.front(); q.pop();
res.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
return res;
}
};

C++ 代码 - leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
层次遍历
*/
class Solution {
public:
vector<int> decorateRecord(TreeNode* root) {
vector<int> res;
if (!root) return res;

queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
res.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
return res;
}
};

剑指32:从上到下打印二叉树
https://lcf163.github.io/2021/01/31/剑指32:从上到下打印二叉树/
作者
乘风的小站
发布于
2021年1月31日
许可协议