#include "Tree.h"
using namespace std;
bool isBSTNODE(Node* h, Node* n, int value)
{
if(h == nullptr)
return false;
if(h == n)
return true;
return isBSTNODE(h->value > value ? h->left : h->right, n, value);
}
int maxTopo(Node* h, Node* n)
{
if(h && n && isBSTNODE(h, n, n->value))
{
return maxTopo(h, n->left) + maxTopo(h, n->right) + 1;
}
return 0;
}
int bstTopoSize1(Node* head)
{
if(head == nullptr)
return 0;
int imax = maxTopo(head, head);
imax = max(bstTopoSize1(head->left), imax);
imax = max(bstTopoSize1(head->right), imax);
return imax;
}
struct record
{
int L;
int R;
record(int data1, int data2) : L(data1), R(data2) {}
};
int posOrder(Node* head, map<Node*, record*>& nrMap);
//flag用来判断调整左边界还是右边界
int modifyMap(Node* head, int value, map<Node*, record*>& nrMap, bool flag);
int bstTopoSize2(Node* head)
{
map<Node*, record*> nrMap;
return posOrder(head, nrMap);
}
int posOrder(Node* head, map<Node*, record*>& nrMap)
{
if(head == nullptr)
return 0;
int ls = posOrder(head->left, nrMap);
int rs = posOrder(head->right, nrMap);
modifyMap(head->left, head->value, nrMap, true);
modifyMap(head->right, head->value, nrMap, false);
record* lr = nrMap.find(head->left) != nrMap.end() ? nrMap[head->left] : nullptr;
record* rr = nrMap.find(head->right) != nrMap.end() ? nrMap[head->right] : nullptr;
int lbst = lr == nullptr ? 0 : lr->L + lr->R + 1;
int rbst = rr == nullptr ? 0 : rr->L + rr->R + 1;
if(nrMap.find(head) != nrMap.end())
{
nrMap[head]->L = lbst;
nrMap[head]->R = rbst;
}
else
{
record* r = new record(lbst, rbst);
nrMap[head] = r;
}
return max(lbst + rbst + 1, max(ls, rs));
}
int modifyMap(Node* head, int value, map<Node*, record*>& nrMap, bool flag)
{
if(head == nullptr || nrMap.find(head) == nrMap.end())
return 0;
record *r = nullptr;
r = nrMap[head];
if((flag && head->value > value) || (!flag && head->value < value))
{
nrMap.erase(head);
return r->L + r->R + 1;
}
else
{
int minus = modifyMap(flag ? head->right : head->left, value, nrMap, flag);
if(flag)
{
r->R = r->R - minus;
}
else
{
r->L = r->L - minus;
}
nrMap[head] = r;
return minus;
}
}
int main()
{
Node* pNode0 = new Node(0);
Node* pNode1 = new Node(5);
Node* pNode2 = new Node(2);
Node* pNode3 = new Node(3);
Node* pNode4 = new Node(6);
Node* pNode5 = new Node(7);
Node* pNode6 = new Node(8);
connectTree(pNode0, pNode1, pNode2);
connectTree(pNode1, pNode3, pNode4);
connectTree(pNode2, pNode5, pNode6);
cout << bstTopoSize2(pNode0) << endl;
cout << bstTopoSize1(pNode0) << endl;
}
找到二叉树中符合搜索二叉树条件的最大拓扑结构
猜你喜欢
转载自blog.csdn.net/wzc2608/article/details/80777389
今日推荐
周排行