The Wayback Machine - https://web.archive.org/web/20241128014835/https://www.geeksforgeeks.org/tournament-tree-and-binary-heap/
Open In App

Tournament Tree (Winner Tree) and Binary Heap

Last Updated : 02 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a team of N players. How many minimum games are required to find the second-best player?  

We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the internal node represents the winner. 

In a tournament tree, every internal node contains the winner and every leaf node contains one player. There will be N – 1 internal node in a binary tree with N leaf (external) nodes. 

For details see this post (put n = 2 in the equation given in the post). It is obvious that to select the best player among N players, (N – 1) players are to be eliminated, i.e. we need a minimum of (N – 1) games (comparisons). Mathematically we can prove it. In a binary tree, I = E – 1, where I is a number of internal nodes and E is a number of external nodes. It means to find the maximum or minimum element of an array, we need N – 1 (internal nodes) comparisons. 

Second Best Player The information explored during best player selection can be used to minimize the number of comparisons in tracing the next best players. For example, we can pick the second-best player in (N + log2N – 2) comparisons. The following diagram displays a  tournament tree (winner tree) as a max heap. Note that the concept of the loser tree is different. 

 

The above tree contains 4 leaf nodes that represent players and have 3 levels 0, 1, and 2. Initially, 2 games are conducted at level 2, one between 5 and 3 and another one between 7 and 8. In the next move, one more game is conducted between 5 and 8 to conclude the final winner. Overall we need 3 comparisons. 

For the second-best player we need to trace the candidates who participated with the final winner, which leads to 7 as the second-best. 

Median of Sorted Arrays Tournament tree can effectively be used to find the median of sorted arrays. Assume, given M sorted arrays of equal size L (for simplicity). We can attach all these sorted arrays to the tournament tree, one array per leaf. We need a tree of height CEIL (log2M) to have at least M external nodes. Consider an example. Given 3 (M = 3) sorted integer arrays of maximum size 5 elements.

{ 2, 5, 7, 11, 15 } ---- Array1
{1, 3, 4} ---- Array2
{6, 8, 12, 13, 14} ---- Array3

What should be the height of the tournament tree? We need to construct a tournament tree of height log23 .= 1.585 = 2 rounded to the next integer. A binary tree of height 2 will have 4 leaves to which we can attach the arrays as shown in the below figure.

  

After the first tournament, the tree appears as below,

We can observe that the winner is from Array2. Hence the next element from Array2 will dive in and games will be played along the winner path of the previous tournament. 

Note that infinity is used as a sentinel element. Based on data being held in nodes, we can select the sentinel character. For example, we usually store the pointers in nodes rather than keys, so NULL can serve as a sentinel. If any of the array exhausts we will fill the corresponding leaf and upcoming internal nodes with sentinel. After the second tournament, the tree appears as below, 

 

The next winner is from Array1, so the next element of the Array1 array which is 5 will dive into the next round, and the next tournament played along the path of 2. The tournaments can be continued till we get the median element which is (5+3+5)/2 = 7th element. 

Note that there are even better algorithms for finding the median of the union of sorted arrays, for details see the related links given below. 

In general with M sorted lists of size L1, L2 … Lm requires time complexity of O((L1 + L2 + … + Lm) * logM) to merge all the arrays and O(m*logM) time to find median, where m is median position. 

elect the smallest one million elements from one billion unsorted elements: As a simple solution, we can sort a billion numbers and select the first one million. On a limited memory system sorting a billion elements and picking the first one million seems to be impractical. We can use the tournament tree approach. At any time only elements of a tree are in memory. 

Split the large array (perhaps stored on disk) into smaller size arrays of size one million each (or even smaller that can be sorted by the machine). Sort these 1000 small size arrays and store them on disk as individual files. Construct a tournament tree that can have at least 1000 leaf nodes (tree to be of height 10 since 29 < 1000 < 210, if the individual file size is even smaller we will need more leaf nodes). Every leaf node will have an engine that picks the next element from the sorted file stored on disk. 

We can play the tournament tree game to extract the first one million elements. Total cost = sorting 1000 lists of one million each + tree construction + tournaments.

Application of Tournament Trees:

  • Used for sorting purposes.
  • Used to find the largest and smallest element 
  • It may also be used in m-way merges
  • Applied in the Truck Loading problem

Implementation: 

We need to build the tree in a bottom-up manner. All the leaf nodes were filled first. Start at the left extreme of the tree and fill along the breadth (i.e. from 2k-1 to 2k – 1 where k is the depth of the tree) and play the game. After practicing with a few examples it will be easy to write code. Implementation is discussed in the below code Second minimum element using minimum comparisons

Related Posts : Find the smallest and second smallest element in an array. Second minimum element using minimum comparisons — by Venki. 


Previous Article
Next Article

Similar Reads

Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Maximum points difference between the winner and runner up of Tournament
Given integer N and K, denoting the number of teams participating in a football tournament where each team plays only one match with each other team, the task is to find the maximum point difference between the winner and the runner-up (second place holder) of the tournament where the winner of a match gets K points. Examples: Input: N = 2, K = 4Ou
4 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property states that it should be A Complete Binary Tree. For
4 min read
Given number of matches played, find number of teams in tournament
Given an integer M which is the number of matches played in a tournament and each participating team has played a match with all the other teams. The task is to find how many teams are there in the tournament.Examples: Input: M = 3 Output: 3 If there are 3 teams A, B and C then A will play a match with B and C B will play a match with C (B has alre
5 min read
Order of teams in a tournament such that every team has won against its consecutive team
Given N teams and the results of round-robin tournament in which no match resulted is draw or tie. The task is to find the order of the teams such that every team has won against its consecutive team. Examples: Input: N = 4 results[] = {{1, 4}, {4, 3}, {2, 3}, {1, 2}, {2, 1}, {3, 1}, {2, 4}} Output: 2 4 3 1 Explanation: Team-2 has won against Team-
9 min read
Organizing Tournament Problem
Given a positive integer N representing the count of players playing the game. The game is played between two teams such that each team consists of at least one player but the total count of players in the game must be N. The game lasts in exactly 30 minutes, the task is to check if all players will play the game against each other or not If the ga
8 min read
Find maximum possible point scored by team at Kth rank in league tournament
There are N teams numbered from 1 to N in a league tournament. Given an integer K, the task is to find the maximum possible points a team finishing at Kth position can score. It is given that, a team will get 2 points on winning while 0 points on losing. Note: A league tournament is also known as round-robin tournament where each team plays with ev
5 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Find the winner of a game where scores are given as a binary string | Set 2
Given a binary string str representing the scores of a Volleyball match. The task is to find the winner of the match according to below conditions: In volleyball, the two teams play with each other and the team which scores 15 points first will be the winner except the case when both teams have reached to 14 points.In the case when both teams have
4 min read
Find winner in the game of Binary Array
Given a binary array X[] of size N. Two players A and B are playing games having the following rules, then the task is to determine the winner if B starts first and both players play optimally. The rules are: In the first turn, a player selects any index i (1 â‰Ī i â‰Ī N) such that A[i] = 0.After their first move, a player can choose an index, which is
7 min read
Find the winner of a game where scores are given as a binary string
Given a binary string representing the scores of a Volleyball match. The task is to find the winner of the match according to below conditions: In volleyball, the two teams play with each other and the team which scores 15 points first will be the winner except the case when both teams have reached to 14 points.In the case when both teams have reac
8 min read
Height of a complete binary tree (or Heap) with N nodes
Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we take a few examples, we can notice that the value of
3 min read
Check if a given Binary Tree is a Heap
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. all levels except the last should be full).Every node’s value should be greater than or equal to its child node (considering max-heap).Examples: Input: Output: True Input: Output: F
15+ min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Predict the winner of a card game of removing K cards in each turn such that Bitwise AND of K and size of pile is 0
There are two players A and B and a pile of N cards stacked upon each other. The task is to find the winner of the game, assuming both players play optimally as per the following guidelines: Player A always begins the game and the players take alternate turns subsequently.In each turn, a player can remove K( 1 ? K ? N) cards if K & n = 0, where
8 min read
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Find winner of game where simultaneous decrement and increment of two elements done in one move
Given an arr[] of positive integers of length N. Player X and Y plays a game where in each move one person chooses two elements of arr[] (say arr[i] and arr[j]) such that 0 ? i < j ? N - 1 and arri should be greater than 0 and Then decrement arri and increment arrj. When one player is unable to make such a move the player loses. The task is to f
7 min read
Find the winner of game where X picks 1, then Y picks 2, then X picks 3 and so on
Two players X and Y are picking up numbers alternatively with X picking first. In the first turn X picks 1, then Y picks 2, then X picks 3 and the game goes on like this. When a player cannot pick a number he loses the game. Given 2 integers A and B denoting the maximum sum of the numbers X and Y can pick respectively. Find the winner of the game.
12 min read
Find the winner between N and M based on the Integer Subtraction
Given two integers N and M. Two players A and B are playing the game on these integers. The task is to output the winner if A starts first and last the player who makes the last moves wins. Any player is allowed to make the following move: Choose one integer from N or M, then subtract a multiple of the non-chosen integer from the chosen integer suc
8 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Print all the leaf nodes of Binary Heap
Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: 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
7 min read
Check if Binary Heap is completely filled
Given an integer N which denotes the number of elements in a binary heap. Check if the binary Heap is completely filled or not. Examples: Input: 7Output: YESExplanation: At height = 0, no. of elements = 1At height = 1, no. of elements = 2At height = 2, no. of elements = 4 Last level is completely filled because at level 2 we need 22 = 4 elements to
4 min read
What is Binary Heap
Binary heap is a complete binary tree where the root of any subtree has a higher (or lower based on the type of heap) value than all the nodes in its subtree. Characteristics of Binary Heap: The following are the properties of a binary heap: It is a complete binary tree, which means that all levels of the tree are completely filled, with the except
2 min read
How to check if a given array represents a Binary Heap?
Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: arr[] = {9, 15, 10, 7, 12, 11} Output: False The giv
11 min read
Array Representation Of Binary Heap
A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as array. The representation is done as: The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: Arr[(i-1)/2] Returns the parent node Arr[(2*i)+1] Returns the left child node Arr[(2*i)+2] Returns the right child node
1 min read
three90RightbarBannerImg