ACM - 根据前序遍历的字符数组求中序遍历

ACM - 根据前序遍历的字符数组求中序遍历

题目解释

即首先根据输入的字符数组构建二叉树,然后对其进行中序遍历。

输入:
	数组元素的个数与字符数组,各字符间以空格进行间隔
输出:
	对应二叉树的中序遍历结果

代码

#pragma once
#include<iostream>
#include<vector>
using namespace std;

typedef char TDataType;
//二叉树节点  二叉链
typedef struct BNode
{
	BNode *_left;
	BNode *_right;
	TDataType _data;
};

class BTree
{
public:
	BTree()
		:_root(nullptr)
	{}
	//创建一个二叉树,数组的顺序为前序遍历
	//比如前序遍历的数组“ABD##E#H##CF##G##”,其中 # 代指空树
	BTree(vector<TDataType> arr, int *idx)
	{
		_root = createBTree(arr, idx);
	}
	BNode *createBTree(vector<TDataType> arr, int *idx)
	{
		if ((*idx) > arr.size()-1)
			return NULL;
		if (arr[*idx] == '#')
		{
			(*idx)++;
			return NULL;
		}
		
		BNode *root = (BNode*)malloc(sizeof(BNode));
		root->_data = arr[*idx];
		(*idx)++;

		root->_left = createBTree(arr, idx);
		root->_right = createBTree(arr, idx);
		return root;
	}

	~BTree()
	{
		if (_root)
			BTreeDestory(&_root);
	}

	void inOrder(BNode *root)
	{
		if (root)
		{
			inOrder(root->_left);
			cout << root->_data << " ";
			inOrder(root->_right);
		}
	}

	void BTree::BTreeDestory(BNode **root)
	{
		if (*root)
		{
			BTreeDestory(&((*root)->_left));
			BTreeDestory(&((*root)->_right));
			free(*root);
			root = NULL;
		}
	}

	BNode *BTree::BTreeRoot()
	{
		return _root;
	}
private:
	BNode *_root;//二叉树的根节点
};

int main()
{
	int n;
	cin >> n; // 数组的个数
	//vector<char> arr={ '1', '2', '#',  '3','#' };
	vector<char> arr;
	for (int i = 0; i < n; i++)
	{
		char t;
		cin >> t;
		arr.push_back(t);
	}
	int idx = 0;
	BTree bt(arr, &idx);
	cout << "中序遍历:"; bt.inOrder(bt.BTreeRoot()); cout << endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值