Solution 1
直观上就是一个BFS,使用队列管理每一层的遍历节点就可以了。
实现过程中需要注意力两点:
- 注意过滤遍历过程中的空节点
- 一整层需要放在一个数组内,我一开始类似的实现了一个包含vector的queue,发现很浪费,直接每一轮遍历当前队列内所有的节点(一层)就可以了
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入序列的节点个数,线性遍历处理输入
- 空间复杂度: O ( 2 ⌊ log N ⌋ ) O(2^{\lfloor \log N \rfloor}) O(2⌊logN⌋),其中 N N N为输入序列的节点个数,因为最坏情况下,最后一层全满,整个队列最大占用就是最后一层
/**
* 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>> ans;
if (root != nullptr) {
queue<TreeNode*> q;
q.push(root);
ans.push_back({root->val});
// cout << "ROOT " << root->val << endl;
while (!q.empty()) {
int numNodeLevel = q.size();
vector<int> temp;
while (numNodeLevel--) {
auto now = q.front();
q.pop();
// cout << "NOW " << now->val << endl;
auto left = now->left;
if (left != nullptr) {
temp.push_back(left->val);
// cout << "LEFT " << left->val << endl;
q.push(left);
}
auto right = now->right;
if (right != nullptr) {
temp.push_back(right->val);
// cout << "RIGHT " << right->val << endl;
q.push(right);
}
}
if (!temp.empty()) {
ans.push_back(temp);
}
}
}
return ans;
}
};
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = list()
if root is not None:
q = collections.deque([root])
ans.append([root.val])
while q:
numNodeLevel = len(q)
temp = list()
while numNodeLevel:
now = q.popleft()
left, right = now.left, now.right
if left is not None:
temp.append(left.val)
q.append(left)
if right is not None:
temp.append(right.val)
q.append(right)
numNodeLevel -= 1
if len(temp) > 0:
ans.append(temp)
return ans