之字折线二叉树遍历C++

ZigZag binary tree traversal in C++

本文关键字:遍历 C++ 二叉树 折线      更新时间:2023-10-16

我正在尝试二叉树的锯齿形遍历。但是我被困在一种类型的测试用例上,即当树不平衡时。如果我把我的输入作为

3
3 9 20 null null 15 7

对于看起来像这样的二叉树:

3
/ 
9  20
/  
15   7

我得到输出:

3 
20 9 
0 

如果我的输入是 3 9 20 1 null 15 7,我的输出是: 3 20 9 1 0

下面是我的代码。

struct node
{
int data;
node* left;
node* right;
};
void order (node* root, map <int, vector <int> >& ans, int level, int k) {
if (root == NULL) {
return;
}
if (k==0) {
if (root->left != NULL) {
ans[level+1].push_back(root->left->data);
order (root->left, ans, level+1, 1);
}
if (root->right != NULL) {
ans[level+1].push_back(root->right->data);
order (root->right, ans, level+1, 1);
}
}
else if (k==1) {
order (root->left, ans, level+1, 0);
order (root->right, ans, level+1, 0);
if (root->right != NULL)
ans[level+1].push_back(root->right->data);
if (root->left != NULL)
ans[level+1].push_back(root->left->data);
}
}
vector<vector<int> > zigzag(node* root){
map <int, vector <int> > ans;
vector <vector <int> > zig;
ans[0].push_back(root->data);
order(root, ans, 1, 1);
for (auto it = ans.begin(); it != ans.end(); it++ ) {   //converting map into vector
zig.push_back(it->second);
}
return zig;
}

据我了解,如果输入为空,我的代码应该不返回任何内容并继续执行更多节点。我无法弄清楚我的错误。有人可以帮助我吗? 啪!

您的代码实际上似乎与您提供的测试用例一起使用。我怀疑您的问题与输入/输出有关。然而,不幸的是,解决方案本身并非如此。请考虑以下测试用例:

1
/ 
5   2
/     
6       3
/         
7           4

您的解决方案将输出:[[1]、[5, 2]、[6, 3]、[7, 4]]

让我们将锯齿形向量中的每个向量称为一个级别。

  1. 首先,将 1(根(添加到第一级。
  2. k==1
  3. 级别==1 然后你递归左。
  4. k==
  5. 0 级别==2 将 6 正确添加到级别 2。并再次递归离开。
  6. k==
  7. 1 级别==3 不能向左或向右递归。将 7 错误地添加到级别 3。返回
  8. k==
  9. 0 级别==2 不能递归对。返回。
  10. k==1 级别
  11. ==1 将 5 错误地添加到级别 1。递归权。
  12. 等。

我认为这种方法很难找到正确的解决方案。主要是因为它的DFS性质。BFS解决方案可能是正确的途径。它自然适合这些逐级样式的问题。

对于关卡顺序遍历,您可以使用堆栈数据结构以锯齿形方式遍历每个关卡。

vector<vector<int> > Solution::zigzagLevelOrder(TreeNode* root) {
stack<TreeNode*> s1, s2;
s1.push(root);
vector< vector< int> > ans;
int check = 1;
while(!s1.empty() or !s2.empty()){
vector<int> current;
if(check){
while(!s1.empty()){
root = s1.top();
s1.pop();
current.push_back(root->val);
if(root->left)
s2.push(root->left);
if(root->right)
s2.push(root->right);
}
check = 1 - check;
}
else{
while(!s2.empty()){
root = s2.top();
s2.pop();
current.push_back(root->val);
if(root->right)
s1.push(root->right);
if(root->left)
s1.push(root->left);
}
check = 1 - check;
}
ans.push_back(current);
}
return ans;
}

维护奇数级别的第一个堆栈和偶数级别的第二个堆栈。在穿越奇数级时,先推左子级然后向右推,在遍历偶数关卡时推右子级然后向左推。