从给定的有序和预序遍历构造二叉树
Constructing Binary tree from given inorder and preorder traversals
我正在从给定的有序和预序遍历数组中制作二叉树,我不知道为什么它会给我错误的输出,尽管它对于给定数组中的某些点来说是完美的
#include<iostream>
using namespace std;
class Node
{
public:
int i;
Node* left;
Node* right;
bool isThreaded;
Node(int j);
};
Node::Node(int j):i(j)
{
left=NULL;
right=NULL;
}
void inorder(Node* root)
{
if(root)
{
inorder(root->left);
cout<<root->i<<" ";
inorder(root->right);
}
}
int findkey(int* a, int l, int r, int key)
{
for(int i=l; i<r; i++)
{
if(a[i]==key)
return i;
}
return -1;
}
Node* ConstructfromPreorderInorder(int* pre, int n, int* in, int l, int r, int& k)
{
Node* root=NULL;
if(k<n && l<r)
{
int key=findkey(in, l, r, pre[k]); //Finds the index of current preorder element in inorder array
root=new Node(pre[k++]); //Forms the node
root->left=ConstructfromPreorderInorder(pre, n, in, 0, key, k); //To find the left subtree we traverse to left of the index of element in inroder array
root->right=ConstructfromPreorderInorder(pre, n, in, key+1, r, k);
//Similarly we traverse right to form right subtree
}
return root;
}
int main()
{
int pre[]={1,2,4,5,3,6,7};
int in[]={4,2,5,1,6,3,7};
int n=sizeof(pre)/sizeof(*pre); //Function used to find the no. of elements in an array. In this case elements in preorder array. Both are same so can use any
int i=0;
Node* root2=ConstructfromPreorderInorder(pre, n, in, 0, n, i);
inorder(root2);
}
虽然它适用于数组中一半的元素,但它会给出不寻常的结果。我已经添加了打印语句,以便更好地查看。
构造左子树范围应该从1开始,而不是从0开始
root->left=ConstructfromPreorderInorder(pre, n, in, l, key, k);
root->left=ConstructfromPreorderInorder(pre, n, in, 0, key, k);
您的潜在问题的答案,"我如何调试这段代码?":
- 查找最简单的故障情况
- 分别测试部分代码,如
findkey
。 - 在你的脑海中慢慢地看一遍。
- 在调试器中逐步调试。
- 添加详细打印语句。
最后一个例子:
Node* ConstructfromPreorderInorder(int* pre, int n, int* in, int l, int r,
int& k)
{
cout << "constructing from " << l << " to " << r << " at " << k << endl;
相关文章:
- 二叉树级别顺序遍历在leetcode中
- 使用二叉树的关卡顺序概念的垂直顺序遍历
- 之字折线二叉树遍历C++
- 二叉树级别顺序遍历 LeetCode
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 二叉树顺序遍历在C++
- C++,如何创建和绘制二叉树,然后按预购方式遍历它
- 二叉树顺序遍历错误:没有用于调用的匹配函数
- 基于矢量的二叉树遍历
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 如何遍历二叉树并在不传递值的情况下计算值的出现次数
- 使用递归的顺序二叉树遍历与使用堆栈的优缺点
- 使用递归的顺序和预序遍历 - 二叉搜索树 C++
- 遍历二叉搜索树C++
- 从序遍历和预序遍历构造二叉树的时间复杂性
- 使用级别顺序遍历将节点插入二叉树
- 递归后序遍历解除分配二叉树节点
- 遍历二叉树的函数
- 无法使用非递归顺序方法遍历二叉树
- 是否可以使用迭代而不是递归来遍历二叉树?