Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

need ur help plz

hi every body,,,i am new and this is first time i write,,,,
i have question i dont know how to write it
i should write a method called public nodeLevel(int k) which returns how many nodes in level k.
i have already wtrite the class binary tree ...
thank u
:)
[287 byte] By [moon_light] at [2007-11-11 8:35:13]
# 1 Re: need ur help plz
What you will be performing is a breadth first search and using a queue to track the nodes visited and the node levels. [This is a classic kind of BFS solved task.] You will count the number of nodes which are at level "k" - either visit all the nodes at level k-1 and tally their children, or actually visit the nodes at level "k" and tally your count as you visit them.

If you really wanted (needed) to, you could do this as a depth first search, to traverse down to each sucessor at level "k".
nspils at 2007-11-11 22:34:59 >
# 2 Re: need ur help plz
i ve written this it is ok or not??

public nodelevel(int k){
if(root == null)
return 0;
else
return getnodelevel(root, 1);
}

private int getnodelevel(TreeNode root, int k){
if(root == null)
return 0;
else
return level +getnodelevel(root.left, k) + getnodelevel(root.right,k);
}
moon_light at 2007-11-11 22:35:53 >
# 3 Re: need ur help plz
That's a nice recursive determining the depth of the tree. How are you going to capture the number of nodes at each level?
nspils at 2007-11-11 22:36:57 >
# 4 Re: need ur help plz
ok can u help me with this plz :)
moon_light at 2007-11-11 22:38:02 >
# 5 Re: need ur help plz
What can you do to store (in your nodeLevel method) the values being returned by your getNodeLevel method? Once you have those values stored, what can you do to obtain a count of the number of nodes at level "k"?
nspils at 2007-11-11 22:39:01 >
# 6 Re: need ur help plz
i don't know how to complete it??
moon_light at 2007-11-11 22:40:05 >
# 7 Re: need ur help plz
You would perform a breadth first search -

go to root, put it into a queue, add a value that it is level 0
whle the queue is not empty,
pop the root node off the queue, visit each of its children, pushing them onto the queue, noting they are level 1
pop each first child off the queue, increment your count of level 1 nodes, visit each of its chidren, pushing them onto the queue adding a note that they are level 2.
when all level 1 nodes are off the queue,
pop each grandchildren child off the queue, increment your count of level 2 nodes, visit each of their chidren, pushing them onto the queue adding a note that they are level 3.
when all level 2 nodes are off the queue,
etc.
nspils at 2007-11-11 22:40:58 >
# 8 Re: need ur help plz
How are you building your binary tree?
nspils at 2007-11-11 22:42:07 >
# 9 Re: need ur help plz
what do you mean?
i have already write the binary tree
moon_light at 2007-11-11 22:43:04 >