二叉树建立与删除代码
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct tree
{
char data;
struct tree* left;
struct tree* right;
}TREE;
TREE* SetUp(TREE* root);
TREE* Print(TREE* root);
void Delete(TREE* root);
int main(void)
{
TREE* root = NULL;
root=SetUp( root);
root=Print(root);
Delete(root);
return 0;
}
TREE* SetUp( TREE* root)
{
char ch;
cin >> ch;
TREE* node = new TREE;
if (ch != '0')
{
node->data = ch;
node->left = SetUp(node);
node->right = SetUp(node);
}
else
node = NULL;
return node;
}
TREE *Print(TREE* root)
{
if (root != NULL)
{
cout << root->data;
Print(root->left);
Print(root->right);
}
return root;
}
void Delete(TREE* root)
{
if (root->left != NULL)
Delete(root->left);
if (root->right != NULL)
Delete(root->right);
delete root;
}
根据先序遍历建立二叉树然后中序遍历打印
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct tree
{
char data;
struct tree* l, * r;
}TREE;
TREE* SetUp();
void Print(TREE* root);
//void Delete(TREE* root);
int main(void)
{
TREE* root = NULL;
root=SetUp();
Print(root);
//Delete(root);
return 0;
}
TREE* SetUp()
{
char ch;
cin >> ch;
TREE* node;
if (ch != '0')
{
node = new TREE; //新建节点,申请内存
node->data = ch;
node->l = SetUp();
node->r = SetUp();
}
else
node = NULL;
return node;
}
void Print(TREE* root)
{
if (root != NULL)
{
Print(root->l);
cout << root->data;
Print(root->r);
}
}