Q4.6

本文介绍了如何使用自定义二叉搜索树实现最小化树构造,并详细阐述了如何通过该树查找两个指定节点的最近公共祖先。通过递归算法和树的遍历,读者可以理解数据结构的应用和算法优化。
#include <iostream>
using namespace std;

const int maxn = 100;

struct Node
{
	int data;
	Node *lchild, *rchild, *parent;
};

Node *p, *head, node[maxn];
int cnt = 0;

void Init()
{
	p = head = NULL;
	memset(node, '\0', sizeof(node));
}

void miniTree(Node* &head, Node *parent, int a[], int lower, int upper)
{
	if(lower <= upper)
	{
		int mid = (lower + upper) >> 1;
		node[cnt].data = a[mid];
		node[cnt].parent = parent;
		head = &node[cnt++];   //key
		miniTree(head->lchild, head, a, lower, mid - 1);
		miniTree(head->rchild, head, a, mid + 1, upper);
	}
}

bool hasNode(Node *p, Node *n)
{
	if(n == NULL)
		return true;
	if(p == NULL)
		return false;
	if(p == n)
		return true;
	return hasNode(p->lchild, n) || hasNode(p->rchild, n);	
}

Node* firstAncestor(Node *head, Node *target1, Node *target2)
{
	if(head == NULL)
		return NULL;
	if(!hasNode(head, target1) || !hasNode(head, target2))
		return NULL;
		
	Node *re = head;
	if(hasNode(head->lchild, target1) && hasNode(head->lchild, target2))
		re = firstAncestor(head->lchild, target1, target2);
	else if(hasNode(head->rchild, target1) && hasNode(head->rchild, target2))
		re = firstAncestor(head->rchild, target1, target2);
	return re;		
}

int main(void) 
{
	Init();
	int a[] = {
		1, 2, 3, 4, 5, 6, 7, 8, 9, 10
	};
	int len = sizeof(a) / sizeof(int);
	miniTree(head, p, a, 0, len - 1);
	
	Node *target1 = &node[2];
	Node *target2 = &node[9];
	Node *re = firstAncestor(head, target1, target2);
	
	cout << re->data << endl;
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值