原题连接: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
首先用一个队列来存储结点,首先将根节点入队
只要队列不为空,就进入循环
取出队头p,输出p,如果p有左右孩子,就将左右孩子入队(如果要求从右到左只要修改这里就好)
循环的次数就是树的高度,每次循环都能输出当前一层的遍历结果
C++代码:
/**
* 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>> result;
// 存储每层结点的队列 先把根结点入队
queue<TreeNode*> que;
if(root != NULL)
que.push(root);
// 每次循环处理一层 循环的次数就是树的高度
while(!que.empty()){
// 本层结点数
int n = que.size();
// tmp存储一层的结果
vector<int> tmp;
for(int i = 0; i < n; i++ ){
auto x = que.front();
que.pop();
tmp.push_back(x->val);
// 如果有左右孩子
if(x->left) que.push(x->left);
if(x->right) que.push(x->right);
}
// 将这一层的结果放入result中
result.push_back(tmp);
}
return result;
}
};
复杂度分析:
- 时间复杂度:O(n),每个结点都入队、出队一次
- 空间复杂度:O(n),队列中的元素不超过所有结点数