简体   繁体   English

AVL树的最大和最小节点

[英]AVL Tree max and min node

how do i get the max and min number of nodes in an AVL tree when given the height of 8. 给定高度为8时,如何获取AVL树中的最大和最小节点数。

i can't seem to be able to trace it out properly from the formula f(8)=f(7)+f(6)+1 我似乎无法从公式f(8)= f(7)+ f(6)+1正确地找到它

2*f(6)+f(5)+2
2*[f(5)+f(4)+1]+f(5)+2
3*f(5)+2*f4+4
3*[f(4)+f(3)+1]+2*f(4)+4
5*f(4)+3*f(3)+7
5*[f(3)+f(2)+1]+3*f(3)+7
8*f(3)+5*f(2)+12
8*[f(2)+f(1)+1]+5*f(2)+12
13*f(2)+8*f(1)+20
13*[f(1)+f(0)+1]+8*f(1)+20
21*f(1)+13*f(0)+33=54 whereas answer is 88 is the minimum

For every node in AVL tree we know that the depths of the left and the right subtree differs by at most 1 (this is given by definition). 对于AVL树中的每个节点,我们知道左子树和右子树的深度最多相差1(由定义给出)。

From that, the next step is quite obvious : we take the minimum trees of depths N and N - 1 and place them as subtrees for a new root. 由此可见,下一步非常明显:我们选取深度为N和N-1的最小树并将其作为新根的子树。 It's clear that the AVL rules still hold and that the tree is contains as little nodes as possible (obvious from the induction base case). 显然,AVL规则仍然成立,并且树包含尽可能少的节点(从归纳基本案例中可以明显看出)。

From that, we've got the recursion formula : minnodes(depth) = 1 + minnodes(depth-1) + minnodes(depth - 2). 由此,我们得到了递归公式:minnodes(depth)= 1 + minnodes(depth-1)+ minnodes(depth-2)。 That's a simple recursive equation, Wolfram Alpha can solve that for you ( link ). 那是一个简单的递归方程,Wolfram Alpha可以为您解决这个问题( 链接 )。

The second case is trivial - a perfect binary tree of depth h contains as many nodes as possible for the depth given and trivially satisfies the AVL conditions. 第二种情况是微不足道的-深度为h的完美二叉树包含给定深度的尽可能多的节点,并且满足AVL条件。

You miscalculated a step somewhere, looks like near the end: 您在某个地方计算了错误的步骤,看起来快要结束了:

f(0) = 1
f(1) = 2
f(2) = f(1) + f(0) + 1 = 4
f(3) = f(2) + f(1) + 1 = 4 + 2 + 1 = 7
f(4) = f(3) + f(2) + 1 = 7 + 4 + 1 = 12
f(5) = f(4) + f(3) + 1 = 12 + 7 + 1 = 20
f(6) = f(5) + f(4) + 1 = 20 + 12 + 1 = 34
f(7) = f(6) + f(5) + 1 = 34 + 20 + 1 = 55
f(8) = f(7) + f(6) + 1 = 55 + 34 + 1 = 88

And if you don't believe it, you can always cook up a quick snippet to check: 而且,如果您不相信它,可以随时制作一个简短的代码段进行检查:

@Test
public void testGetMax() {
    assertEquals(88, getMax(8));
}

int getMax(int x) {
    switch (x) {
        case 0:
            return 1;
        case 1:
            return 2;
        default:
            return getMax(x - 1) + getMax(x - 2) + 1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM