Zok - 1 year ago 76
Java Question

# Assigning distinct values to leaves in a tree

I am trying to assign numbers to each leaf in a tree.

For example if we have a tree that has 6 leaves, I want the leaves to have the numbers from 0 to 5.

I don't know why my code doesn't work well, I have been trying many times even in recursive ways but it seems I am missing something..

public class Node {

int index;
int id;
Node left;
Node right;

// Constructor and setters/getters.

public static void num(Node n) {

int ini=0;
if(n==null)
{

}
if(n.isLeaf())
{
n.index=ini;
ini++;
}
if(!n.isLeaf())
{
num(n.getleft());
num(n.getRight());
}
}

Also I wanted to get the number of the leaves in the tree.

For example, Our tree looks like

1
/ \
2 3
/ \ / \
6 9 8 10
/
4
public static int numberChild(Node n, int count)

{
if (n == null) {
return 0;
}
if (n.getleft() == null && n.getRight() == null) {
return 1 + count;
} else {
int lc = numberChild(n.getleft(), count);
int rc = numberChild(n.getRight(), lc);
return rc;
}

}

will give me a wrong number of leaves, 2 instead of 4 !

Any Help ?