题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
代码
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 思想:
# 采用BFS,队列实现,注意返回列表维度
# 复杂度:
# O(N)
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res, Q = [], collections.deque() # 此处采用双端队列,出入队复杂度由O(N)降为O(1)
Q.append(root) # 根入队
while Q:
tmp=[]
for _ in range(len(Q)):
node = Q.popleft()
tmp.append(node.val) # 压入子列表
if node.left: Q.append(node.left) # 左子树入队
if node.right: Q.append(node.right) # 右子树入队
res.append(tmp) # 压入结果列表
return res
C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode* > Q;
if (!root) return res;
Q.push(root);
while (Q.size()) {
int size=Q.size();
vector<int> tmp;
for (int i=0; i<size; i++) {
TreeNode* node=Q.front();
Q.pop();
tmp.push_back(node->val);
if (node->left) Q.push(node->left);
if (node->right) Q.push(node->right);
}
res.push_back(tmp);
}
return res;
}
};