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);
}
# 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 >
