Balanced binary tree (recursive)

Balanced binary tree (recursive)

Playing time taking into account the left sub-tree filled, the number of tree nodes right child as little as possible, and then to find "the number of nodes as little as possible" when thinking wrong.

n> d + 1, with recursion to solve. Consider height is n, the number of left and right subtrees of nodes does not exceed the least of the nodes tree d, so that the number of nodes f (n) of the tree left subtree and right subtree, respectively, are balanced, and should the number of nodes try to be less, then we make the number of child tree nodes left to f (n-1), the number of right child node is f (n-1-d) to meet the conditions.

When n <= d + 1 when, f (n) = n.

According to this idea has been finished only had 70% of the sample. And then I found (1ll << (n-1)) of this thing, is transformed into a check 1ll long long, in which someone else's code, then written to know their original burst of int.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll f[65];
int n,d;

int main()
{
    cin>>n>>d;
    ll lchild=0,rchild=0;
    if(n>0)
        lchild=(1ll<<(n-1))-1;
    for(int i=1;i<=n;i++)
    {
        if(i<=d+1)
            f[i]=i;
        else
            f[i]=f[i-1]+f[i-1-d]+1;
    }
    if(n>0)
        rchild=f[n-1-d];
    cout<<lchild-rchild<<endl;
}

 

Guess you like

Origin blog.csdn.net/xuzonghao/article/details/82935854