Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

math - What is the total number of nodes in a full k-ary tree, in terms of the number of leaves?

I am doing a unique form of Huffman encoding, and am constructing a k-ary (in this particular case, 3-ary) tree that is full (every node will have 0 or k children), and I know how many leaves it will have before I construct it. How do I calculate the total number of nodes in the tree in terms of the number of leaves?

I know that in the case of a full binary tree (2-ary), the formula for this is 2L - 1, where L is the number of leaves. I would like to extend this principle to the case of a k-ary tree.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Think about how to prove the result for a full binary tree, and you'll see how to do it in general. For the full binary tree, say of height h, the number of nodes N is

N = 2^{h+1} - 1

Why? Because the first level has 2^0 nodes, the second level has 2^1 nodes, and, in general, the kth level has 2^{k-1} nodes. Adding these up for a total of h+1 levels (so height h) gives

N = 1 + 2 + 2^2 + 2^3 + ... + 2^h = (2^{h+1} - 1) / (2 - 1) = 2^{h+1} - 1

The total number of leaves L is just the number of nodes at the last level, so L = 2^h. Therefore, by substitution, we get

N = 2*L - 1

For a k-ary tree, nothing changes but the 2. So

N = 1 + k + k^2 + k^3 + ... + k^h = (k^{h+1} - 1) / (k - 1)

L = k^h

and so a bit of algebra can take you the final step to get

N = (k*L - 1) / (k-1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...