Saturday, March 8, 2014

Find rightmost elements at each level of binary tree


// - Find height(h) of binary tree and define the array of size h.
// - Traverse the binary tree and store the elements of each level at the array index of level

static void rightSideElements(Node root){

int level = 0;
int h = heightBT(root);
int arr[] = new int[h];
rightSideUtil(root, level, arr);
for(int i = 0; i<arr.length; i++)
{
System.out.print(arr[i]+", ");
}
}

private static void rightSideUtil(Node root, int level, int[] a){

if(root == null) return;

a[level] = root.data;

rightSideUtil(root.left, level+1, a);
rightSideUtil(root.right, level+1, a);

}