【问题标题】:Random insertion to left or right in binary tree在二叉树中向左或向右随机插入
【发布时间】:2018-01-23 18:24:51
【问题描述】:

我在将节点随机插入二叉树时遇到问题,我知道二叉树的基本实现,但是我从未在程序中使用过 typedef 枚举,事实上这是我第一次曾经不得不使用它。谁能指出我将如何在我的程序中实现 typedef 语句的正确方向,以便在右子树或左子树中随机创建一个新节点?

这是我必须使用的 typedef 语句,但不知道如何使用。

 typedef enum { left_side, right_side } SIDE;
 SIDE rnd ( ) { return rand ( ) % 2 ? right_side : left_side; }

这是我的二叉树类和插入函数。

template < class T > class binTree {
    public:
        binTree ( ); // default constructor
        unsigned height ( ) const; // returns height of tree
        virtual void insert ( const T& ); // inserts a node in tree
        void inorder ( void ( * ) ( const T& ) ); // inorder traversal of tree
    protected:
        Node < T >* root; // root of tree
    private:
        unsigned height ( Node < T >* ) const; // private version of height ( )
        void insert ( Node < T >*&, const T& ); // private version of insert ( )
        void inorder ( Node < T >*, void ( * ) ( const T& ) ); // private version of inorder ( )
};

 // inserts a node in shortest subtree
template <class T>
void binTree <T>::insert( const T& v )
{ //thi is how i am used to  inserting into binary trees
    insert( root, v ); // call recursive
}

//private version of insert
template <class T>
void binTree <T>::insert( Node <T>* & p, const T& v )
{

     if( p == NULL )
     {
        Node <T> * newNode;
        newNode = new Node <T>( v ); // new node with new value
        p = newNode; // set ptr to new node
     }

    else
    {
        int lHeight = height( p->left );
        int rHeight = height( p->right );

        if( lHeight <= rHeight )
        {
            insert( p->left, v );
        }
        else
        {
            insert( p->right, v );
        }
    }
}

【问题讨论】:

    标签: c++ random tree insert binary-tree


    【解决方案1】:

    这样使用

    template <class T>
    void binTree<T>::insert( Node<T>*& p, const T& v){
    
    if (p == NULL)
    root = new Node<T> (v);
    
    else{
    SIDE s = rnd();
      if(s == left_side)
      insert(p->left, v);
      else
      insert(p->right,v);
    
      }
    }
    

    【讨论】:

    • 我不得不对第一个 if 语句进行一些更改,但是 SIDE 的实现是正确的,非常感谢,我真的很感激我不会弄明白但现在我理解 typedef 枚举部分为很好,完成了我的程序。
    • 我忘了把我的根变量改成你的变量名'p',这就是为什么它可能会让你有点困惑。但我很高兴能帮上忙!这个程序来自 NIU csci 340 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多