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;
}


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


总结

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

### PTA平台上的完全二叉搜索实现方法 在PTA平台上解决与完全二叉搜索Complete Binary Search Tree, CBST)相关的问题时,通常需要结合二叉搜索的特性和完全二叉树的性质来设计算法。以下是关于如何实现在PTA上处理CBST的一些关键点: #### 1. **完全二叉搜索的定义** 完全二叉搜索是一种特殊的二叉搜索,它不仅满足二叉搜索的特性——即每个节点的左子中的所有键值均小于该节点的键值,而右子中的所有键值均大于该节点的键值[^3];还具有完全二叉树的形状特点:除了最后一层外,其他各层都被填满,并且最后一层的所有节点都尽可能靠左排列。 #### 2. **构建完全二叉搜索的方法** 为了构建一个完全二叉搜索,可以采用如下策略: - 将输入的数据先排序。 - 使用治法递归地构造,每次选取中间位置作为当前层次的根节点,左侧部构成左子,右侧部构成右子。 ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def sorted_array_to_bst(nums): if not nums: return None mid = len(nums) // 2 root = TreeNode(nums[mid]) root.left = sorted_array_to_bst(nums[:mid]) # 构建左子 root.right = sorted_array_to_bst(nums[mid+1:]) # 构建右子 return root ``` 此代码片段展示了如何通过已排序数组创建平衡的二叉搜索,从而间接形成完全二叉搜索[^4]。 #### 3. **验证是否为完全二叉搜索** 验证一棵是否为完全二叉搜索涉及两个方面: - 验证其是否为有效的二叉搜索- 检查其结构是否符合完全二叉树的要求。 可以通过广度优先遍历(BFS)检测是否存在任何违反完全二叉树规则的情况。如果发现某个非叶子节点有右孩子却没有左孩子,或者在遇到第一个缺失的孩子之后还有新的孩子节点,则说明这不是一颗完全二叉树。 #### 4. **删除操作优化** 当涉及到删除节点时,在保持完全性的前提下执行删除会更加复杂。一般做法是在找到待删除节点后,将其替换为其前驱或后继节点,并调整剩余部以维持完全性[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

迷途-归处

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

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

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

打赏作者

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

抵扣说明:

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

余额充值