1167 Cartesian Tree——建树和层序遍历

 

分析

给出小顶堆的中序,输出层序

因此只需要每次找出序列中最小的,即为父结点

 

代码

#include<bits/stdc++.h>
using namespace std;

struct Tree {
	int key;
	Tree* lchild,* rchild;
	Tree(int x) {
		key = x;
		lchild = rchild = NULL;
	}
};
int quantity;
vector<int>heap_ordered;

Tree* BuildTree(Tree*, int, int);
void LevelPrint(Tree*);
int main() {
	scanf("%d", &quantity);
	heap_ordered.resize(quantity);
	for (int i = 0; i < quantity; i++)
		scanf("%d", &heap_ordered[i]);
	Tree* root{ NULL };
	root = BuildTree(root, 0, quantity - 1);
	LevelPrint(root);
	return 0;
}
Tree* BuildTree(Tree* T,int left,int right) {
	if (right - left < 0)
		return T;
	auto x = min_element(heap_ordered.begin() + left, heap_ordered.begin() + right + 1) - heap_ordered.begin();
	T = new Tree(heap_ordered[x]);
	T->rchild = BuildTree(T->rchild, x + 1, right);
	T->lchild = BuildTree(T->lchild, left, x - 1);
	return T;
}
void LevelPrint(Tree* T) {
	queue<Tree*>temp;
	temp.push(T);
	bool flag{ true };
	while (1) {
		flag ? printf("%d", T->key), flag = false : printf(" %d", T->key);
		if (T->lchild != NULL)
			temp.push(T->lchild);
		if (T->rchild != NULL)
			temp.push(T->rchild);
		temp.pop();
		if (!temp.empty())
			T = temp.front();
		else
			break;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值