之字折线二叉树遍历C++
ZigZag binary tree traversal in C++
我正在尝试二叉树的锯齿形遍历。但是我被困在一种类型的测试用例上,即当树不平衡时。如果我把我的输入作为
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(根(添加到第一级。 k==1
- 级别==1 然后你递归左。 k==
- 0 级别==2 将 6 正确添加到级别 2。并再次递归离开。 k==
- 1 级别==3 不能向左或向右递归。将 7 错误地添加到级别 3。返回 k==
- 0 级别==2 不能递归对。返回。 k==1 级别
- ==1 将 5 错误地添加到级别 1。递归权。
- 等。
我认为这种方法很难找到正确的解决方案。主要是因为它的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;
}
维护奇数级别的第一个堆栈和偶数级别的第二个堆栈。在穿越奇数级时,先推左子级然后向右推,在遍历偶数关卡时推右子级然后向左推。
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 避免在遍历 IShellItemArray 时出现代码重复
- 从特定键开始遍历地图
- 关于链表遍历和调试的困惑
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 二叉树级别顺序遍历在leetcode中