1、题目描述:
2、题解:
BFS
在处理每一层时,一口气处理完。
python代码:
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# BFS
res = []
if not root:
return res
queue = collections.deque()
queue.append(root)
while queue:
temp = []
size = len(queue)
for _ in range(size):
node = queue.popleft()
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
return res
C++代码:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int currentLevelSize = q.size();
res.push_back(vector<int>());
for (int i =1;i <= currentLevelSize;++i){
auto node = q.front();q.pop();
res.back().push_back(node->val);
if(node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
};
或者:
/**
* 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) {
// BFS
vector<vector<int>> res;
queue<TreeNode*> q;
if (!root){
return res;
}
q.push(root);
while (!q.empty()){
int size = q.size();
vector<int> temp;
for(int i = 0;i < size;i++){
TreeNode* node = q.front();
q.pop();
temp.push_back(node->val);
if (node->left){
q.push(node->left);
}
if(node->right){
q.push(node->right);
}
}
res.push_back(temp);
}
return res;
}
};
3、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)