04-树6 Complete Binary Search Tree (30 分)

  1. 这道题除了陈越姥姥上课讲的思路之外,还有另一种思路:完全二叉搜索树的中序遍历是顺序序列,已知当前的顺序序列,可以倒推出原来的完全二叉搜索树。

  2. 下面的代码填写的是姥姥讲的思路,通过公式计算他们的左儿子、右儿子的个数。
    计算左子树的规模

  3. input数组为已经排好序的完全二叉树,output为未排序待输出数组,如下图所示:
    总体思路

     #include <iostream>
     #include <algorithm>
     #include <cmath>
     using namespace std;
     const int maxn = 1001;
     int input[maxn], output[maxn];
     int getLeftLength(int n) {
     	double h = log(n + 1) / log(2.0);
     	int H = (int)h;
     	int x = floor(n + 1 - pow(2.0, H));
     	int x_2 = floor(pow(2.0, H - 1));
     	x = min(x, x_2);
     	return (int)(pow(2.0, H - 1) + x-1);
     }
     
     
     
     
     void solve(int left, int right, int root) {
     	//初始调用为solve(0,n-1,0)
     	int n = right - left + 1;
     	if (n == 0)return;
     	int L = getLeftLength(n);
     	output[root] = input[L + left];
     	int leftoutputRoot = root * 2 + 1;//左儿子结点在数组的下标
     	int rightoutputRoot = root * 2 + 2;
     	solve(left, L + left-1, leftoutputRoot);//递归解决左儿子
     	solve(L + left + 1, right, rightoutputRoot);//递归解决右儿子
     
     }
     
     
     
     
     int main() {
     	int n;
     	cin >> n;
     	for (int i = 0; i < n; i++) {
     		cin >> input[i];
     	}
     	sort(input, input + n);
     	//cout<<getLeftLength(n);
     	solve(0, n - 1, 0);
     	cout << output[0];
     	for (int i = 1; i < n; i++) {
     		cout << " " << output[i];
     	}
     	system("pause");
     	return 0;
     }
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值