您的位置:首页 > 编程语言 > C语言/C++

数组生成MaxTree——C++

2016-02-24 18:42 253 查看

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;
}`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: