HDU 2193 AVL Tree
AVL Tree
An AVL tree is a kind of balanced binary search tree. Named after their inventors, Adelson-Velskii and Landis, they were the first dynamically balanced trees to be proposed. Like red-black trees, they are not perfectly balanced, but pairs of sub-trees differ in height by at most 1, maintaining an O(logn) search time. Addition and deletion operations also take O(logn) time.Definition of an AVL tree
An AVL tree is a binary search tree which has the following properties:
1. The sub-trees of every node differ in height by at most one.
2. Every sub-tree is an AVL tree.
Balance requirement for an AVL tree: the left and right sub-trees differ by at most 1 in height.An AVL tree of n nodes can have different height.
For example, n = 7:
So the maximal height of the AVL Tree with 7 nodes is 3.
Given n,the number of vertices, you are to calculate the maximal hight of the AVL tree with n nodes.
Input
Input file contains multiple test cases. Each line of the input is an integer n(0<n<=10^9).
A line with a zero ends the input.
Output
An integer each line representing the maximal height of the AVL tree with n nodes.Sample Input
1 2 0
Sample Output
0 1
解題思路:
本題給出一個整數,要求輸出其能建立的最高的平衡二叉樹的高度。
關於平衡二叉樹最小節點最大高度有一個公式,設height[i]為高度為i的平衡二叉樹的最小結點數,則height[i] = height[i - 1] + height[i - 2] + 1;
因為高度為0時平衡二叉樹:
#
高度為1時平衡二叉樹:
0 # 或 #
/ \
1 # #
高度為2時平衡二叉樹:
0 # 或 #
/ \ / \
1 # # # #
/ \
2 # #
高度為i時平衡二叉樹:
# 或 #
/ \ / \
i - 2 i - 1 i - 1 i - 2
所以只需要將10^9內的數據記錄後讓輸入的數據與之比較就可得到答案。(高度不會超過46)
1 #include <cstdio> 2 using namespace std; 3 const int maxn = 50; 4 int height[maxn]; 5 int main(){ 6 height[0] = 1; 7 height[1] = 2; 8 for(int i = 2; i < maxn; i++){ //記錄1 - 50層最小需要多少節點 9 height[i] = height[i - 1] + height[i - 2] + 1; 10 } 11 int n; 12 while(scanf("%d", &n) != EOF){ //輸入數據 13 if(n == 0) //如果為0結束程序 14 break; 15 int ans = -1; 16 for(int i = 0; i < maxn; i++){ //從第0層開始比較 17 if(n >= height[i]) //只要輸入的數據大於等於該點的最小需求答案高度加一 18 ans++; 19 else 20 break; //否則結束循環 21 } 22 printf("%d\n", ans); //輸出答案 23 } 24 return 0; 25 }
HDU 2193 AVL Tree