给定一个N个元素的数组,该数组表示二进制堆的数组表示形式,任务是查找此二进制堆的叶节点。
例子:
Input:
arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: 4 5 6 7
Explanation:
1
/ \
2 3
/ \ / \
4 5 6 7
Leaf nodes of the Binary Heap are:
4 5 6 7
Input:
arr[] = {1, 2, 3, 4, 5,
6, 7, 8, 9, 10}
Output: 6 7 8 9 10
Explanation:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /
8 9 10
Leaf Nodes of the Binary Heap are:
6 7 8 9 10
方法:该问题的主要观察结果是,如果H是二进制堆的高度,则二进制堆的每个叶节点都将位于高度H或H -1 。因此,叶节点可以如下计算:
- 计算二进制堆的总高度。
- 以相反的顺序遍历数组,并将每个节点的高度与Binary Heap的计算高度H进行比较。
- 如果当前节点的高度为H,则将当前节点添加到叶节点。
- 否则,如果当前节点的高度为H-1并且没有子节点,则还将该节点添加为叶节点。
下面是上述方法的实现:
Java
// Java implementation to print
// the leaf nodes of a Binary Heap
import java.lang.*;
import java.util.*;
class GFG {
// Function to calculate height
// of the Binary heap with given
// the count of the nodes
static int height(int N)
{
return (int)Math.ceil(
Math.log(N + 1)
/ Math.log(2))
- 1;
}
// Function to find the leaf
// nodes of binary heap
static void findLeafNodes(
int arr[], int n)
{
// Calculate the height of
// the complete binary tree
int h = height(n);
ArrayList arrlist
= new ArrayList<>();
for (int i = n - 1; i >= 0; i--) {
if (height(i + 1) == h) {
arrlist.add(arr[i]);
}
else if (height(i + 1) == h - 1
&& n <= ((2 * i) + 1)) {
// if the height if h-1,
// then there should not
// be any child nodes
arrlist.add(arr[i]);
}
else {
break;
}
}
printLeafNodes(arrlist);
}
// Function to print the leaf nodes
static void printLeafNodes(
ArrayList arrlist)
{
for (int i = arrlist.size() - 1;
i >= 0; i--) {
System.out.print(
arrlist.get(i) + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };
findLeafNodes(arr, arr.length);
}
}
C#
// C# implementation to print
// the leaf nodes of a Binary Heap
using System;
using System.Collections.Generic;
class GFG{
// Function to calculate height
// of the Binary heap with given
// the count of the nodes
static int height(int N)
{
return (int)Math.Ceiling(
Math.Log(N + 1) /
Math.Log(2)) - 1;
}
// Function to find the leaf
// nodes of binary heap
static void findLeafNodes(int []arr,
int n)
{
// Calculate the height of
// the complete binary tree
int h = height(n);
List arrlist = new List();
for (int i = n - 1; i >= 0; i--)
{
if (height(i + 1) == h)
{
arrlist.Add(arr[i]);
}
else if (height(i + 1) == h - 1 &&
n <= ((2 * i) + 1))
{
// if the height if h-1,
// then there should not
// be any child nodes
arrlist.Add(arr[i]);
}
else
{
break;
}
}
printLeafNodes(arrlist);
}
// Function to print the leaf nodes
static void printLeafNodes(List arrlist)
{
for (int i = arrlist.Count - 1; i >= 0; i--)
{
Console.Write(arrlist[i] + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };
findLeafNodes(arr, arr.Length);
}
}
// This code is contributed by Princi Singh
输出:
6 7 8 9 10
性能分析:
- 时间复杂度: O(L),其中L是叶节点的数量。
- 辅助空间: O(1)