I'm writing a binary tree class, and I'm stuck on a levelCount method, where I need to count the number of nodes on a level of the tree. The class and method look something like this:
public class ConsTree<T> extends BinaryTree<T>
{
BinaryTree<T> left;
BinaryTree<T> right;
T data;
public int levelCount(int level)
{
}
}
So the idea is that each tree has a tree to its left, a tree to its right, and data. There is an abstract class binarytree and subclasses ConsTree and EmptyTree.
I think I need to use a breadth first search and count the number of nodes once I get to that level, but I'm stuck on how to start. Any guidance here would be helpful. I can provide any other info necessary.
Here's the general approach.
You traverse the tree exactly as you would normally (depth-first, in-order) but you simply pass down the desired and actual level as well, with pseudo-code such as:
def getCountAtLevel (node, curr, desired):
# If this node doesn't exist, must be zero.
if node == NULL: return 0
# If this node is at desired level, must be one.
if curr == desired: return 1
# Otherwise sum of nodes at that level in left and right sub-trees.
return getCountAtLevel (node.left, curr+1, desired) +
getCountAtLevel (node.right, curr+1, desired)
#######################################################################
# Get number of nodes at level 7 (root is level 0).
nodesAtLevel7 = getCountAtLevel (rootNode, 0, 7)
It doesn't actually traverse the entire tree since, once it gets to the desired level, it can just ignore everything underneath that. Here's a complete C program that shows this in action:
#include <stdio.h>
typedef struct _sNode { struct _sNode *left, *right; } tNode;
// Node naming uses (t)op, (l)eft, and (r)ight.
tNode t_l_l_l = {NULL, NULL }; // level 3
tNode t_l_l_r = {NULL, NULL };
tNode t_r_l_l = {NULL, NULL };
tNode t_r_l_r = {NULL, NULL };
tNode t_r_r_r = {NULL, NULL };
tNode t_l_l = {&t_l_l_l, &t_l_l_r}; // level 2
tNode t_r_l = {&t_r_l_l, &t_r_l_r};
tNode t_r_r = {NULL, &t_r_r_r};
tNode t_l = {&t_l_l, NULL }; // level 1
tNode t_r = {&t_r_l, &t_r_r };
tNode t = {&t_l, &t_r }; // level 0 (root)
static int getCAL (tNode *node, int curr, int desired) {
if (node == NULL) return 0;
if (curr == desired) return 1;
return getCAL (node->left, curr+1, desired) +
getCAL (node->right, curr+1, desired);
}
int main (void) {
for (int i = 0; i < 4; i++)
printf ("Level %d has %d node(s)\n", i, getCAL (&t, 0, i));
return 0;
}
It builds a tree of the following form:
__X__
/ \
X X
/ / \
X X X
/ \ / \ \
X X X X X
and then gives you the node count at each level:
Level 0 has 1 node(s)
Level 1 has 2 node(s)
Level 2 has 3 node(s)
Level 3 has 5 node(s)
来源:https://stackoverflow.com/questions/12879903/binary-tree-counting-nodes-on-a-level