数组生成MaxTree——C++

来源:互联网 发布:高收益网络国债信托 编辑:程序博客网 时间:2024/06/03 07:50

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;}`
0 0
原创粉丝点击