求一个二叉树中最大的二分搜索子树---C++实现

#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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值