I.
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
没什么好说的,BFS+队列。
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int> v;
if (root == nullptr) return v;
queue<TreeNode> q;
vector<int> ans;
q.push(*root);
while (!q.empty()) {
TreeNode head = q.front();
q.pop();
ans.push_back(head.val);
if (head.left != nullptr) {
q.push(*(head.left));
}
if (head.right != nullptr) {
q.push(*(head.right));
}
}
return ans;
}
};
II.
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
加个变量来标记每一层的结点位置就好。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == nullptr) return ans;
vector<int> v;
TreeNode q[3000];
int head = 0;
int tail = 0;
int cnt = 0;
q[tail++] = *root;
cnt++;
while (head < tail) {
TreeNode tmp = q[head++];
v.push_back(tmp.val);
if (tmp.left != nullptr) {
q[tail++] = *(tmp.left);
}
if (tmp.right != nullptr) {
q[tail++] = *(tmp.right);
}
if (head == cnt) {
cnt = tail;
ans.push_back(v);
v.clear();
}
}
return ans;
}
};
III.
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
再加一个变量,0/1之间来回变动,标记此次是正序还是倒序。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == nullptr) return ans;
vector<int> v;
TreeNode q[3000];
int head = 0;
int tail = 0;
int cnt = 0;
bool flag = true;
q[tail++] = *root;
cnt++;
while (head < tail) {
TreeNode tmp = q[head++];
v.push_back(tmp.val);
if (tmp.left != nullptr) {
q[tail++] = *(tmp.left);
}
if (tmp.right != nullptr) {
q[tail++] = *(tmp.right);
}
if (head == cnt) {
if (flag) {
cnt = tail;
ans.push_back(v);
v.clear();
flag = false;
}
else {
cnt = tail;
reverse(v.begin(), v.end());
ans.push_back(v);
v.clear();
flag = true;
}
}
}
return ans;
}
};