I have made a function to calculate the number of element(nodes) of Non-Binary Tree, but it always return the correct answer - 1 (eg if the number of element is 10 it returns 9) like I am missing calculting the root. I spent hours trying to fix it and it did not work!
Here is the part of my code where I build the tree:
NaryTreeNode<Integer> iRoot = new NaryTreeNode<Integer>(25);
NaryTreeNode<Integer> i1 = new NaryTreeNode<Integer>(11);
NaryTreeNode<Integer> i2 = new NaryTreeNode<Integer>(-23);
NaryTreeNode<Integer> i3 = new NaryTreeNode<Integer>(67);
NaryTreeNode<Integer> i4 = new NaryTreeNode<Integer>(-7);
NaryTreeNode<Integer> i5 = new NaryTreeNode<Integer>(88);
NaryTreeNode<Integer> i6 = new NaryTreeNode<Integer>(47);
NaryTreeNode<Integer> i7 = new NaryTreeNode<Integer>(91);
NaryTreeNode<Integer> i8 = new NaryTreeNode<Integer>(-34);
NaryTreeNode<Integer> i9 = new NaryTreeNode<Integer>(15);
iRoot.addChild(i1);
iRoot.addChild(i2);
iRoot.addChild(i3);
i1.addChild(i4);
i1.addChild(i5);
i2.addChild(i6);
i4.addChild(i7);
i4.addChild(i8);
i4.addChild(i9);
LinkedNaryTree<Integer> iTree = new LinkedNaryTree<Integer>(iRoot);
System.out.println(iTree.size(iTree.getRoot()));
Here is the code of my method:
public int size(NaryTreeNode<T> node) {
if (node == null)
return 0;
int counter = 0;
for (int i = 0; i < node.getNumChildren(); i++) {
counter += 1 + size(node.getChild(i));
}
return counter;
}
The reason you get 1 less is that you account for a node outside of the function call ( 1 + size()
), yet a call to size
should include in its count the node you pass as argument.
So there are two places where you need a fix:
int counter = 0;
should be int counter = 1;
so to account for node
, which we already know at that point is not null.
counter += 1 + size(node.getChild(i));
on the other hand is counting 1 too many. Here I think you intended with that 1 +
to account for the child, but size()
should include in its returned count the child itself (done by the fix above). So this should just be:
counter += size(node.getChild(i));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.