问题描述
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)