#include "pch.h"
#include <iostream>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
/*
求结点个数最多的满足二分搜素树的子树
*/
typedef struct btree {
struct btree* lchild;
struct btree* rchild;
int data;
btree(int data) {
lchild = rchild = NULL;
this->data = data;
}
}node;
struct ReturnType {
int max;
int min;
int size;
node* cur_head;
ReturnType(int max, int min, int size, node* head) {
this->max = max;
this->min = min;
this->size = size;
this->cur_head = head;
}
ReturnType() {
this->max = (-1) << 31;
this->min = 1 << 30;
this->size = 0;
this->cur_head = NULL;
}
};
ReturnType* getMaxBST(node* root) {
if (root == NULL) {
return new ReturnType;
}
else {
ReturnType* leftType = getMaxBST(root->lchild);
ReturnType* rightType = getMaxBST(root->rchild);
int cur_size = 0;
if (((root->data > leftType->max) && (root->data < rightType->min))
&& (root->lchild == leftType->cur_head)
&& (root->rchild == rightType->cur_head)
){
cur_size = leftType->size + rightType->size + 1;
int cur_max = max(max(leftType->max, rightType->max), root->data);
int cur_min = min(min(leftType->min, rightType->min), root->data);
return new ReturnType(cur_max, cur_min, cur_size, root);
}
else {
int cur_max = max(max(leftType->max, rightType->max), root->data);
int cur_min = min(min(leftType->min, rightType->min), root->data);
if (rightType->size > leftType->size) {
return new ReturnType(cur_max, cur_size, rightType->size, rightType->cur_head);
}
return new ReturnType(cur_max, cur_size, leftType->size, leftType->cur_head);
}
}
}
void inorder(node* root) {
if (root) {
inorder(root->lchild);
cout << root->data << " ";
inorder(root->rchild);
}
}
求一个二叉树中最大的二分搜索子树---C++实现
最新推荐文章于 2021-11-16 13:24:03 发布