【问题标题】:Insert element into BinaryTree recursively递归地将元素插入二叉树
【发布时间】:2016-07-17 15:18:39
【问题描述】:

我尝试编写以下方法以递归方式将节点插入二叉树。该策略基本上是在任何 NULL 左或右指针中插入节点。

typedef struct BinaryTreeNode {
int data;
BinaryTreeNode * left;
BinaryTreeNode * right;
} BinaryTreeNode;

void InsertElementInBinaryTree(BinaryTreeNode *root, BinaryTreeNode *element) {
    if(root) {
         if(root -> left == NULL) root -> left = element;
         else if(root -> right == NULL) root -> right = element;
         InsertElementInBinaryTree(root -> left, element);
         InsertElementInBinaryTree(root -> right, element);
    }
}

方法在main函数中调用如下

InsertElementInBinaryTree(&root , new BinaryTreeNode{8, NULL,NULL});

问题是这个调用总是返回一个分段错误错误,所以我相信错误是在递归中?

【问题讨论】:

  • 当使用动态结构(如链表和树)时,您必须使用 malloc() 在堆上保留存储空间,然后才能存储任何数据。您还必须在应用程序退出之前 free() 它,否则重复使用您的应用程序将导致所有堆内存无法使用。

标签: c++ pointers recursion binary-tree


【解决方案1】:

如果您尝试实现二叉树,那么对于任何当前节点,左子树中的所有节点的data 都应该低于当前节点中的data,而右子树中的所有data 应该更大.

void InsertElementInBinaryTree(BinaryTreeNode *&root, BinaryTreeNode *element) {
     if(root == NULL) { root = element; return;}
     if(root -> data > element -> data) 
         InsertElementInBinaryTree(root->left, element);
     else
         InsertElementInBinaryTree(root->right, element);
}

所以实际上data 值定义了element 将插入的位置。此外,我将 BinaryTreeNode *&root 作为参考传递,以便 root 指针可修改。

用法:

// declare root
BinaryTreeNode* root;
// insertion, no & operator before root
InsertElementInBinaryTree(root, new BinaryTreeNode{8, NULL,NULL});

【讨论】:

    【解决方案2】:

    函数可以如下所示

    void InsertElementInBinaryTree( BinaryTreeNode * &root, int data ) 
    {
        if ( root == nullptr )
        {
            root = new BinaryTreeNode { data, nullptr, nullptr };
        }
        else if ( data < root->data )
        {
            InsertElementInBinaryTree( root->left, data );
        }
        else
        {
            InsertElementInBinaryTree( root->right, data );
        }
    }
    

    并像这样称呼

    InsertElementInBinaryTree( root , 8 );
    

    并且对象root最初应该定义为

    BinaryTreeNode *root = nullptr;
    

    【讨论】:

      【解决方案3】:

      您缺少一些条件:

           if (root->data > element->data) {
               if (root->left == NULL) {
                   root->left = element;
               } else {
                   InsertElementInBinaryTree(root->left, element);
               }
           } else {
               if (root->right == NULL) {
                   root->right = element;
               } else {
               InsertElementInBinaryTree(root->right, element);
                }
           }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 2020-07-24
        • 2014-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多