
两个栈
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
stack<TreeNode*> st1,st2;
vector<int> vec;
st1.push(root);
TreeNode* cur = nullptr;
while(1){
while(!st1.empty()){
cur = st1.top();
st1.pop();
vec.push_back(cur->val);
if(cur->left) st2.push(cur->left);
if(cur->right) st2.push(cur->right);
}
if(!vec.empty()){
res.push_back(vec);
vec.clear();
}else{
break;
}
while(!st2.empty()){
cur = st2.top();
st2.pop();
vec.push_back(cur->val);
if(cur->right) st1.push(cur->right);
if(cur->left) st1.push(cur->left);
}
if(!vec.empty()){
res.push_back(vec);
vec.clear();
}else{
break;
}
}
return res;
}
本文介绍了一种使用两个栈实现的锯齿形层次遍历二叉树的算法。首先将根节点压入第一个栈,然后依次弹出栈顶元素并将其值存入临时数组中。随后,如果当前节点有左右子节点,则根据遍历方向的不同,将子节点压入第二个栈。当第一个栈为空时,将临时数组加入结果集中,并清空数组。接下来,重复上述过程,但使用第二个栈进行操作,并改变遍历方向。最终得到的数组即为锯齿形层次遍历的结果。
523

被折叠的 条评论
为什么被折叠?



