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


前言

学习数据结构,记录下过程


一、原题

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input:

10
1 2 3 4 5 6 7 8 9 0
结尾无空行

Sample Output:

6 3 8 1 5 7 9 0 2 4
结尾无空行

简单翻译一下就是构建一个完全二叉树(高度最小,叶节点也是从左到右),最后还要满足满足二叉搜索树,就是左小右大。
可以看到题目就是给十个数,先自己排序,然后按照中序遍历方式填充,就可以得到满足条件的二叉搜索树了,因为中序遍历是左中右嘛,从小到大排好序的数组按照左中右的顺序往完全二叉树里面填,就是题目要求的CBT了,最后层次遍历输出,就是正确结果了。

二、方法

1.常规构建二叉搜索树

刚开始就直接按照常见的二叉树的思路写的,把之前写的二叉树相关的代码裁剪一下(偷个懒),思路是先开一个固定空间的完全二叉树,然后中序遍历往里面填充,最后层序遍历输出。
开CBT空间其实就是层序遍历,得从上到下,从左到右,层序遍历是利用一个队列实现按顺序插入数据,咱这个不用插入数据,就直接一个int size计数就可以了。

template<typename T>
void BinaryTree<T>::Create(const int & size)
{
	int count = size;
	queue<BinTreeNode<T>*> Q;
	BinTreeNode<T>* t = new BinTreeNode<T>;
	Q.push(t);
	if (root != NULL)
		clear();
	root = t;
	for (int i = 1; i < count; i++)
	{
		t = Q.front();
		if (t->leftChild == NULL)
		{
			t->leftChild = new BinTreeNode<T>;
			Q.push(t->leftChild);
		}
		else
		{
			t->rightChild = new BinTreeNode<T>;
			Q.push(t->rightChild);
			Q.pop();
		}
	}
}

中序遍历填充就是在刚刚开辟的空间上遍历,并把队列里的数添加至结点上,代码也是基于中序遍历稍做修改。
最后层序遍历也是老生常谈的函数了。
代码如下(示例):

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
using namespace std;

template <typename T>
class BinTreeNode
{
	typedef T DataType;

public:
	BinTreeNode() { leftChild = NULL; rightChild = NULL; }
	BinTreeNode(T d, BinTreeNode<T> *l, BinTreeNode<T> *r) :data(d), leftChild(l), rightChild(r) {}
	BinTreeNode(BinTreeNode<T> *l, BinTreeNode<T> *r) : leftChild(l), rightChild(r) {}
	T data;
	BinTreeNode<T>* leftChild;
	BinTreeNode<T>* rightChild;
	int height;
};

template <typename T>
class BinaryTree
{
	typedef T DataType;
protected:
	BinTreeNode<T>* root;
private:

	void Destroy(BinTreeNode<T>* current);

	void Create_InOrder(queue<T> &Q, BinTreeNode<T>* cur);

	void LevelOrder(BinTreeNode<T>* current);//按层次遍历

public:
	BinaryTree() { root = NULL; }
	void clear() { Destroy(root); root = NULL; }//删除二叉树
	DataType Root() { return root->data; }//返回根节点数据
	void Create(const int& size);//建立结点个数为size的CBT
	void Create(queue<T> Q);

	void LevelOrder();//按层次遍历


	bool isEmpty() { return root == NULL; }//二叉树是否为空
};


template<typename T>
void BinaryTree<T>::Destroy(BinTreeNode<T>* current)
{
	if (current == NULL)
		return;
	Destroy(current->leftChild);
	Destroy(current->rightChild);
	delete current;
}

template<typename T>
void BinaryTree<T>::Create(queue<T> Q)
{
	Create(Q.size());
	Create_InOrder(Q, root);

}


template<typename T>
void BinaryTree<T>::Create(const int & size)
{
	int count = size;
	queue<BinTreeNode<T>*> Q;
	BinTreeNode<T>* t = new BinTreeNode<T>;
	Q.push(t);
	if (root != NULL)
		clear();
	root = t;
	for (int i = 1; i < count; i++)
	{
		t = Q.front();
		if (t->leftChild == NULL)
		{
			t->leftChild = new BinTreeNode<T>;
			Q.push(t->leftChild);
		}
		else
		{
			t->rightChild = new BinTreeNode<T>;
			Q.push(t->rightChild);
			Q.pop();
		}
	}
}

template<typename T>
void BinaryTree<T>::Create_InOrder(queue<T> &Q, BinTreeNode<T>* cur)
{
	if (cur != NULL)
	{
		Create_InOrder(Q, cur->leftChild);
		cur->data = Q.front();
		Q.pop();
		Create_InOrder(Q, cur->rightChild);
	}
}

template<typename T>
void BinaryTree<T>::LevelOrder()
{
	LevelOrder(root);
}


template<typename T>
void BinaryTree<T>::LevelOrder(BinTreeNode<T>* current)
{
	queue<BinTreeNode<T>*> Q;
	Q.push(current);
	int first = 1;
	while (!Q.empty())
	{
		current = Q.front();//出队
		Q.pop();

		if (first == 1)
		{
			first = 0;
		}
		else
		{
			cout << " ";
		}
		cout << current->data;
		if (current->leftChild)
			Q.push(current->leftChild);
		if (current->rightChild)
			Q.push(current->rightChild);
	}
}

int main()
{
	queue<int> Q;
	vector<int> V;
	int key, count;
	cin >> count;
	BinaryTree<int> tree;

	for (int i = 0; i < count; i++)
	{
		cin >> key;
		V.push_back(key);
	}
	sort(V.begin(), V.end());
	for (auto e : V)
	{
		Q.push(e);
	}
	tree.Create(Q);
	tree.LevelOrder();
	return 0;
}


2.直接利用数组

上述代码纯粹是图个省事,在之前的代码上改了改,应该可以一次中序遍历边创建完全二叉树边赋值,不过那样需要计数确定左子树的范围,要改很多。
直接利用数组其实更方便省事,二叉树可以用数组来表示,而且用数组就只能严格按照完全二叉树的方式来存储,根节点和左子树结点的下标关系是二倍+1的关系,利用数组其实代码就简单很多了。
代码如下:

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
using namespace std;


template <typename T>
void InOrder(vector<T> &V,int index,queue<T> &Q)
{
	if (!Q.empty()&&index<V.size())
	{
		InOrder(V, (index + 1) * 2 - 1, Q);
		V[index] = Q.front();
		Q.pop();
		InOrder(V, (index + 1) * 2 , Q);
	}
}
int main()
{
	queue<int> Q;
	vector<int> V,R;
	int key, count;
	cin >> count;

	
	for (int i = 0; i < count; i++)
	{
		cin >> key;
		V.push_back(key);
	}
	sort(V.begin(), V.end());
	for (auto e : V)
	{
		Q.push(e);
	}

	R.resize(V.size());
	InOrder(R, 0, Q);
	for (int i=0;i<R.size()-1;i++)
	{
		cout << R[i]<<" ";
	}
	cout << R.back();
	return 0;
}


测试点
在这里插入图片描述


总结

记录下数据结构的学习过程吧,希望能促进自己学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷途-归处

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值