Solution 1
其实是 0102. Binary Tree Level Order Traversal 的变体。
向下遍历的过程中,结果的保存方向不同。一开始我还想用两个队列实现(或者双向队列,因为每一次遍历都会清空队列,所以无伤大雅),但是发现实际上只要在结果数组上操作就好了。
此外需要一个遍历一层切换一次的状态变量。
- 时间复杂度: 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>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root != nullptr) {
queue<TreeNode*> q;
q.push(root);
ans.push_back({root->val});
int dir = 0; // 0, left to right; 1, right to left
// cout << "ROOT " << root->val << endl;
while (!q.empty()) {
int numNodeLevel = q.size();
vector<int> temp;
dir ^= 1;
// cout << "DIR " << dir << endl;
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()) {
if (dir == 0) {
ans.push_back(temp);
} else {
ans.push_back(vector<int>{temp.rbegin(), temp.rend()});
}
}
}
}
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 zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = list()
if root is not None:
q = collections.deque([root])
ans.append([root.val])
dir = 0
while q:
numNodeLevel = len(q)
temp = list()
dir ^= 1
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:
if dir == 0:
ans.append(temp)
else:
ans.append(temp[::-1])
return ans