这是一般方法。
您完全按照通常的方式遍历树(深度优先,按顺序),但您也只需传递所需的和实际的级别,伪代码如下:
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)
它实际上并没有遍历整个树,因为一旦达到所需的级别,它就可以忽略其下的所有内容。这是一个完整的 C 程序,它显示了这一点:
#include <stdio.h>
typedef struct _sNode { struct _sNode *left, *right; } tNode;
// Node naming uses (t)op, (l)eft, and (r)ight.
tNode TLLL = {NULL, NULL }; // level 3
tNode TLLR = {NULL, NULL };
tNode TRLL = {NULL, NULL };
tNode TRLR = {NULL, NULL };
tNode TRRR = {NULL, NULL };
tNode TLL = {&TLLL, &TLLR }; // level 2
tNode TRL = {&TRLL, &TRLR };
tNode TRR = {NULL, &TRRR };
tNode TL = {&TLL, NULL }; // level 1
tNode TR = {&TRL, &TRR };
tNode T = {&TL, &TR }; // 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 < 5; i++) {
int count = getCAL(&T, 0, i);
printf ("Level %d has %d node%s\n", i, count, (count == 1) ? "" : "s");
}
return 0;
}
它构建以下形式的树(其中T
表示顶部,L
是左分支,R
是右分支):
______T______ (1 node)
/ \
TL TR (2 nodes)
/ / \
TLL TRL TRR (3 nodes)
/ \ / \ \
TLLL TLLR TRLL TRLR TRRR (5 nodes)
(0 nodes)
如果您编译并运行该代码,您会看到它在每个级别提供了正确的节点数:
Level 0 has 1 node
Level 1 has 2 nodes
Level 2 has 3 nodes
Level 3 has 5 nodes
Level 4 has 0 nodes