First of all, if the root is a level 0, then the Knth level of the tree will have nodes N^K. You can start increasing the counter level at a level until you get the nodes M. This way you will find how many levels is this tree consisting of. And the number of leaf nodes is the number of nodes at the last level - this N^lastLevel.
Here is an example: N = 3, M = 4.
First level = 3^0 = 1
Second level = 3^1 = 3
1 + 3 = 4
So, we found that the tree has two levels (counting from 0). Answer: 3^2 = 9.
. , , M : 1 + 3 + 9 + 27 ... = M
, .