data structures - Finding the no of leaf nodes -
an n-ary tree has n sub-nodes each node. if tree has m non-leaf nodes, how find no of leaf nodes?
first of if root level 0
, k
-th level of tree have n^k
nodes. can start incrementing counter level level until m
nodes. way find how many levels tree consisting of. , number of leaf nodes number of nodes on last level - n^lastlevel
.
here example: n = 3, m = 4
.
first level = 3^0 = 1 second level = 3^1 = 3 1 + 3 = 4
so found tree has 2 levels(counting 0). answer 3^2 = 9
.
note: can find level number directly, noticing m
sum of geometric progression: 1 + 3 + 9 + 27 ... = m
hope clear.
Comments
Post a Comment