The number of binary subtree node calculation

Title Description
Here Insert Picture Description
As indicated above, the positive integer 1, 2, ...... constitute a special binary tree. Finally, we know that a node binary tree is n. The question now is where the sub-tree node m in total, including the number of nodes. For example, n = 12, m = 3 then nodes 13, 14 in the figure above and the following nodes are not present, the node where the subtree comprising m nodes have 3,6,7, 12, so the node where m subtree total of four nodes.

Description Input:
Input data comprises a plurality of rows, each row is given a set of test data, includes two integers m, n (1 <= m <= n <= 1000000000).

Description Output:
For each set of test data output line, the line contains an integer, where m is given the number of nodes in the subtree comprised of the nodes.

Example 1
Input
. 3 12 is
0 0
Output
4

Title Analysis: calculating the number of nodes of the binary tree, in which first of all is a complete binary tree, there is a rule, the number of nodes = the number of null node --1; so I use an empty subtree node calculation.
(Of course, you can calculate the number of nodes in an iterative process, the root <time n, + 1. Then about node calculation).

Code:

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<iomanip>
using namespace std; 

int computer(int m,int n){
	if(m > n){
		return 1;
	}else{	
		return computer(2 * m,n) + computer(2 * m + 1, n);
	}
}
int main()
{
	int m , n;
	while(cin >> m >> n){
		
		cout << computer(m,n) - 1 << endl;
	} 
    return 0;
}
Published 41 original articles · won praise 0 · Views 1163

Guess you like

Origin blog.csdn.net/Gedulding/article/details/104325515