# 构造数组的MaxTree

113 篇文章 0 订阅
2 篇文章 0 订阅

//
//  main.cpp
//  构造数组的MAXTree
//
//  Created by zjl on 16/6/2.
//

#include <iostream>
#include <vector>
#include <stack>
#include <map>
using namespace std;

struct Node{
int val;
Node* left;
Node* right;
Node(int data):val(data),left(NULL),right(NULL){}
};

//这是找数的左（右）边最近的比它大的数，并用map存起来
void  stackTomap(stack<Node*>& stk, map<Node*, Node*>& mapleft )
{
Node* temp = stk.top();
stk.pop();
if(stk.empty())
mapleft[temp] = NULL;
else
mapleft[temp] = stk.top();
}

Node* getMaxTree(vector<int> vec){
vector<Node*> v;
for(int i = 0; i < vec.size(); i++)
{
v.push_back(new Node(vec[i]));
}
stack<Node*>stk;
map<Node*, Node*>mapleft, mapright;
for(int i = 0; i < vec.size(); i++){
Node* t = v[i];
while(!stk.empty() && stk.top()->val < t->val)
{
stackTomap(stk, mapleft);
}
stk.push(t);
}
while(!stk.empty())
{
stackTomap(stk, mapleft);
}

for(int j = v.size()-1; j >= 0; j--)
{
Node* t = v[j];
while(!stk.empty() && stk.top()->val < t->val)
stackTomap(stk, mapright);
stk.push(t);
}
while(!stk.empty())
stackTomap(stk, mapright);
for(int k = 0; k < v.size(); k++){
Node* current = v[k];
Node* leftnode = mapleft[current];
Node* rightnode = mapright[current];
if(leftnode == NULL && rightnode == NULL)
else if(leftnode == NULL){
if(rightnode -> left == NULL)
rightnode -> left = current;
else
rightnode -> right = current;
}
else if(rightnode == NULL){
if(leftnode ->left == NULL)
leftnode ->left = current;
else
leftnode ->right = current;
}
else{
Node* parent = leftnode->val > rightnode->val? rightnode:leftnode;
if(parent->left == NULL)
parent->left = current;
else
parent->right = current;
}
}

}

void print_tree(Node* root){
if(root == NULL)
return;
print_tree(root->left);
cout<< root->val<<" ";
print_tree(root->right);
}

int main(int argc, const char * argv[]) {
vector<int>vec = {3,5,4,1,2};
Node* root = getMaxTree(vec);
print_tree(root);
return 0;
}


3 5 4 1 2

3 5 1 2 4

• 0
点赞
• 0
收藏 更改收藏夹
• 打赏
• 0
评论

¥2 ¥4 ¥6 ¥10 ¥20

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