数组生成MaxTree——C++

MaxTree

`class node
{
   public:
    int value;
    node()
    { 
     left = NULL;
     right = NULL;
    }
     ~node(){};
    node( int val )
     {
        value = val;
        left = NULL;
        right = NULL;
     }
     node *left,*right;
};
node* maxTree( int* array,int length ,node* nArr)
{
    if ( !array || length<=0)
     {
        return NULL;
     }
      nArr = new node[length];
     for (int i = 0 ; i < length; i++)
     {
        nArr[i] = node(array[i]);
     }

    node** leftmax = new node*[length];
    node** rightmax = new node*[length];

    // 左边最近、最大的值
    std::stack<node*> nstack;
    for ( int i =0; i < length; i++ )
    {
        while ( !nstack.empty() )
        {
            if ( nArr[i].value >= nstack.top()->value )
            {
                nstack.pop();
            }
            else
            {
                leftmax[i] = nstack.top();
                break;
            }
        }
        if ( nstack.empty() )
        {
            leftmax[i] = NULL;
        }
        nstack.push(&nArr[i]);
    }

    while ( !nstack.empty() )
    {
        nstack.pop();
    }
    // 右边最近、最大的值
    for ( int i =length-1; i >= 0; i-- )
    {
        while ( !nstack.empty() )
        {
            if ( nArr[i].value >= nstack.top()->value )
            {
                nstack.pop();
            }
            else
            {
                node temp = *nstack.top();
                rightmax[i] = nstack.top();
                break;
            }
        }
        if ( nstack.empty() )
        {
            rightmax[i] = NULL;
        }

        nstack.push(&nArr[i]);
    }

    //建立树
    node* head;
    for ( int i = 0; i < length; i++ )
    {
        if ( !leftmax[i] && !rightmax[i] )//左右两边都没有最大值
        {
            head = &nArr[i];
        }
        else if ( !leftmax[i] )//最大值在右边
        {

            if ( !rightmax[i]->left )
                rightmax[i]->left = &nArr[i];
            else
                rightmax[i]->right = &nArr[i];
        }
        else if ( !rightmax[i] )//最大值在左边
        {
            if ( !leftmax[i]->left )
                leftmax[i]->left = &nArr[i];
            else
                leftmax[i]->right = &nArr[i];
        }
        else //左右都有最大值,比较那个值小
        {
            node* parent = (leftmax[i]->value > rightmax[i]->value)? rightmax[i] : leftmax[i];
            if ( !parent->left )
            {
                parent->left = &nArr[i];
            }
            else
            {
                parent->right = &nArr[i];
            }
        }
    }
    delete [] leftmax;
    delete [] rightmax;
    return head;
}`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值