题目解释
即首先根据输入的字符数组构建二叉树,然后对其进行中序遍历。
输入:
数组元素的个数与字符数组,各字符间以空格进行间隔
输出:
对应二叉树的中序遍历结果
代码
#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;
}