常规思路:每层的队列正常处理,隔一行计算结果时反转加入结果数组
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
res=[]
if not root:
return res
stack=[root]
count=0
while stack:
res.append([])
l=len(stack)
for i in range(l):
res[-1].append(stack[i].val)
if stack[i].left:
stack.append(stack[i].left)
if stack[i].right:
stack.append(stack[i].right)
if count==1:
res[-1].reverse()
count=0
else:
count=1
stack=stack[l:]
return res
题解看见的思路,很有意思:两个栈,比如1、3、5行存栈1里,2、4、6存栈2里,栈1每次pop时,左右孩子分别push进栈2,这样栈1中的栈顶元素的左右孩子在栈2的栈底,栈1中的栈底元素的左右孩子在栈2的栈顶,再对栈2pop,pop的左右孩子再push进栈1,就这样交错push/pop。其实就是用两个栈模拟队列,算法导论上看过,不过这里能活学活用还是挺有意思的。
代码很容易,直接把人家代码粘来了,人家的题解地址:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/solution/liang-ge-stackde-jie-fa-bu-xu-fan-zhuan-queuehuo-z
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
//右往左时右先入栈,左往右时,左先入栈。然后要两个栈分别保存每一层级的。
//这里借鉴了树的层次遍历的思想,不过那是用队列
vector<vector<int>> r;
if (!root) return r;
stack<TreeNode *> d1, d2;
d1.push(root);
TreeNode *curr = nullptr;
vector<int> tmp;
while (true) {
while (!d1.empty()) {
curr = d1.top();
d1.pop();
tmp.push_back(curr->val);
if (curr->left) d2.push(curr->left);
if (curr->right) d2.push(curr->right);
}
if (!tmp.empty()) {
r.push_back(tmp);
tmp.clear();
} else break;
while (!d2.empty()) {
curr = d2.top();
d2.pop();
tmp.push_back(curr->val);
if (curr->right) d1.push(curr->right);
if (curr->left) d1.push(curr->left);
}
if (!tmp.empty()) {
r.push_back(tmp);
tmp.clear();
} else break;
}
return r;
};