Created
February 9, 2013 05:25
-
-
Save silverjam/4743992 to your computer and use it in GitHub Desktop.
Given a binary tree return the level with maximum number of nodes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
class Main | |
{ | |
public static void countLevels(Integer tree[], int index, int levels[], int level) | |
{ | |
if ( index >= tree.length ) | |
return; | |
Integer node = tree[index]; | |
if ( node != null ) | |
levels[level] += 1; | |
countLevels(tree, leftChild(index), levels, level+1); | |
countLevels(tree, rightChild(index), levels, level+1); | |
} | |
public static int largestLevel(Integer tree[]) | |
{ | |
int levels[] = new int[numLevels(tree.length)]; | |
for (int x = 0; x < levels.length; x++) | |
levels[x] = 0; | |
countLevels(tree, 0, levels, 0); | |
int max = -1; | |
int maxLevel = -1; | |
for (int level = 0; level < levels.length; level++) | |
{ | |
if ( max < levels[level] ) | |
{ | |
max = levels[level]; | |
maxLevel = level; | |
} | |
} | |
return maxLevel; | |
} | |
public static int numLevels(int nodeCount) | |
{ | |
int log2 = (int) (Math.log(nodeCount+1)/Math.log(2)); | |
return log2; | |
} | |
public static int leftChild(int index) | |
{ return index*2 + 1; } | |
public static int rightChild(int index) | |
{ return index*2 + 2; } | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
/* Given a binary tree return the level with maximum number of nodes | |
0: 1 | |
: / \ | |
1: 2 3 | |
: /\ /\ | |
2: 4 5 6 7 | |
: / \ | |
3: 8 9 | |
returns '2' | |
*/ | |
Integer e = null; | |
System.out.println( | |
largestLevel(new Integer[] { | |
1, | |
2, 3, | |
4, 5, 6, 7, | |
8, e, e, e, e, e, e, 9 } | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment