简体   繁体   English

根据给定的有序和预序遍历构造二叉树

[英]Constructing Binary tree from given inorder and preorder traversals

I am making a binary tree from given inorder and preorder traversal array and I don't know why it is giving me the wrong output although it works perfectly for some points in the given array 我正在从给定的有序和预序遍历数组中生成二叉树,我不知道为什么它给了我错误的输出,尽管它在给定数组中的某些点上可以正常工作

#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);
}

Although it works for the the half of elements in the array but after that it gives unusual results. 尽管它适用于数组中元素的一半,但此后却产生了异常的结果。 I have added print statements for better view. 我添加了打印语句以便更好地查看。

Please see to it if it helps. 请查看是否有帮助。

For constructing left subtree range should start from l instead of 0. 为了构造左子树,范围应从l而不是0开始。

root->left=ConstructfromPreorderInorder(pre, n, in, l, key, k);

instead of 代替

root->left=ConstructfromPreorderInorder(pre, n, in, 0, key, k);

The answer to your underlying question, "How do I debug this code?": 您的基本问题“如何调试此代码?”的答案:

  • Find the simplest possible fail case. 找到最简单的失败案例。
  • Test parts of the code separately, such as findkey . 分别测试代码的各个部分,例如findkey
  • Step through it in your mind. 逐步解决它。
  • Step through it in a debugger. 在调试器中逐步进行调试。
  • Add verbose print statements. 添加详细的打印语句。

Example of the last: 最后一个示例:

Node* ConstructfromPreorderInorder(int* pre, int n, int* in, int l, int  r, 
 int& k)
{
cout << "constructing from " << l << " to " << r << " at " << k << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM