按层逆遍历一棵树,使用满二叉树存储

机试题:
用C语言编写控制台程序。
使用二叉树按层逆遍历输出树的每一个元素。(即从最底层 往 上输出 直到根节点)
要求: 
1,自定义数据结构。使用满二叉树存储输入数据。
2,input: 0,1,2,3,4,5,6,7
   output:7,3,4,5,6,1,2 ,0

 分析:假如树的节点数目为num,则树高为:log(num)/log(2)+1,换底公司,log得到以2为底的log函数,其次int类型会自动截断,只保留整数

                其次,假定根节点为第1层,则第i层的节点编号为:pow(2,i-1)~pow(2,i)-1.

                    因此,只需要从最底层依次往上面遍历就可以了。

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 
 5 
 6 int main()//按层逆遍历一棵树,树使用满二叉树存储,直接用数组就好了
 7 {
 8     int num;
 9     cout << "please input the number of nodes:" << endl;
10     cin >> num;
11     int treeArray[200];
12     memset(treeArray, 0, 200 * sizeof(treeArray[0]));
13     cout << "input the key of each node:" << endl;
14     for (int i = 1; i <= num; i++)
15     {
16         cin >> treeArray[i];
17     }
18     int level = log(num) / log(2) + 1;
19     for (int j = level; j > 0;j--)
20     for (int k = pow(2, j - 1); k <= pow(2, j) - 1; k++)
21     {
22         if (k<=num)
23         cout << treeArray[k] << "   ";
24     }
25 
26     return 0;
27 }
手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
原文地址:https://www.cnblogs.com/chess/p/4675593.html