5.分治-二叉树局部最小

问题描述

Consider an n-node complete binary tree T, where n = 2d−1 for some d. Each node v of T is labeled with a real number xv. You may assume that the real numbers labeling the nodes are all distinct. A node v of T is a local minimum if the label xv is less than the label xw for all nodes w that

are joined to v by an edge. You are given such a complete binary tree T, but the labeling is only specified in the following implicit way: for each node v, you can determine the value xv by probing the node v. Show how to find a local minimum of T using only O(log n) probes to the nodes of T.

翻译

考虑一棵 n 节点的完整二叉树 T,其中 n = 2d-1,为某个 d。可以假设标注节点的实数都是不同的。如果标签 xv 小于通过边与 v 连接的所有节点 w 的标签 xw,则 T 的节点 v 是局部最小值。

的标签 xw。给你这样一棵完整的二叉树 T,但标签只是以如下隐式方式指定的:对于每个节点 v,你可以通过探测节点 v 来确定值 xv。

找二叉树局部最小值

思路

每个节点与左右子树节点做对比,若自己是最小则直接返回,否则递归左右子树,优先递归较小节点

代码

#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <algorithm>
#include <stdlib.h>

using namespace std;
const int N = 1e6 + 10;
int a[N];
/*
			    1
		2		  		3
 	4		5		6		7
 8	  9   10  11   12  13   14 15



 有一个有n个结点的完全二叉树,对于一些d来说n = 2d−1,每一个节点v被标志为一个标签数xv,
 并且每一个xv都是不同的。如果xv小于所有与之相连的标签xw ,那么v被称为局部最小值。
 现在给你一个完全二叉树,但标记只以以下隐式方式指定:对于每个节点v,你可以通过探测节点v来确定值xv。
 展示如何只用O(log n)个探测到T的节点来找到T的局部最小值。
 15 9 8 13 14 12 11 1 1 1 1 1 1 1 1
 3 8
*/
int minmum(int a[], int head,int l, int r)//左节点编号,有结点编号
{
	if (a[head] < a[l] && a[head] < a[r])
		return head;
	if (a[l] < a[r])
		return minmum(a, l, l * 2, l * 2 + 1);
	else
		return minmum(a, r, r * 2, r * 2 + 1);
}
int main()
{
	int n;
	cout << "Please enter The number of nodes n:" << endl;
	cin >> n;
	cout << "Please enter the value of each number (hierarchical traversal approach)" << endl;
	for (int i = 1; i < n; i++)
	{
		cin >> a[i];
	}
	int ans = minmum(a,1,2,3);
	cout << "The lable of local minmum is " << ans << " The value of the local minmum is "<<a[ans];
	return 0;
}

测试案例

运行结果

时间复杂度分析

O(log n)

速记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟人看不到

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值