1064. Complete Binary Search Tree (30)

本文详细介绍了如何构建一个包含n个节点的完全二叉树,并通过中序遍历来获取节点地址数组,进而填充数值。首先,解释了完全二叉树的概念和构建方法;其次,演示了中序遍历的过程,以及如何将已排序的数值数组填充到树结构中;最后,展示了树的层次遍历输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.建议一个n节点的 完全二叉树,然后使用中序遍历,把地址数组遍历出来,再填充数组

2.注意读取的数组需要先排序,在填充到完全二叉树的中序遍历数组中


//#include<string>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include <iomanip>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;
struct TreeNode{
	int val;
	TreeNode*l, *r;
	TreeNode() :val(-1), l(NULL), r(NULL){};
};
void inOrder(TreeNode*root, vector<TreeNode*>&ans)
{
	if (root != NULL)
	{
		inOrder(root->l, ans);
		ans.push_back(root);
		inOrder(root->r, ans);
	}
}
int main(void)
{
	int n;
	cin >> n;
	if (n == 0)
	{
		cout << endl;
		return 0;
	}
	vector<TreeNode> tree(n);
	queue<TreeNode*> q;
	int idx = 0;
	q.push(&tree[idx++]);
	int count1 = 1;
	int count2 = 0;
	//建立一棵节点数为n的完全二叉树
	while (idx < n)
	{
		for (int i = 0; i < count1; i++)
		{
			TreeNode*head = q.front();
			q.pop();
			head->l = &tree[idx++];
			q.push(head->l);
			count2++;
			if (idx == n)
				break;
			head->r = &tree[idx++];
			q.push(head->r);
			count2++;
			if (idx == n)
				break;
		}
		count1 = count2;
		count2 = 0;
	}

	//把树按照中序遍历出一个数组,然后填充数值,主要读取的数组要先排序
	vector<TreeNode*> in(0);
	inOrder(&tree[0], in);
	vector<int> num(n);
	for (int i = 0; i < in.size(); i++)
	{
		scanf("%d", &num[i]);
	}
	sort(num.begin(), num.end());
	for (int i = 0; i < in.size(); i++)
	{
		in[i]->val = num[i];
	}

	queue<TreeNode*> bfs;
	bfs.push(&tree[0]);
	count1 = 1;
	count2 = 0;
	vector<int> ans(0);
	int idxOut = 0;
	while (!bfs.empty())
	{
		for (int i = 0; i < count1; i++)
		{
			TreeNode*head = bfs.front();
			bfs.pop();
			if (idxOut == 0)
				printf("%d", head->val);
			else
				printf(" %d", head->val);
			idxOut++;
			if (head->l != NULL)
			{
				bfs.push(head->l);
				count2++;
			}
			if (head->r != NULL)
			{
				bfs.push(head->r);
				count2++;
			}
		}
		count1 = count2;
		count2 = 0;
	}
	

	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值