#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
typedef struct TreeNode
{
struct TreeNode* lchild, * rchild;
char data;
}RTreeNode;
RTreeNode* CreateTree()
{
char data;
char temp;
RTreeNode* root;
cin >> data;
temp = cin.get();
if (data == '/') {
return NULL;
}
else {
root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (root == NULL)
cout << "Memory allocation failed!" << endl;
else root->data = data;
cout << "Please input left node of " << data << endl;
root->lchild = CreateTree();
cout << "Please input right node of " << data << endl;
root->rchild = CreateTree();
return root;
}
}
int LeafNode(RTreeNode* p)
{
if (!p)
{
return 0;
}
else if (p->lchild == NULL && p->rchild == NULL)
{
return +1;
}
else
{
return LeafNode(p->lchild) + LeafNode(p->rchild);
}
}
int ParentNode(RTreeNode* p)
{
if (!p)
{
return 0;
}
else if (p->lchild == NULL && p->rchild == NULL)
{
return 0;
}
else
{
return ParentNode(p->lchild) + ParentNode(p->rchild) + 1;
}
}
void ParentNodeShow(RTreeNode* p)
{
if (p == NULL)
{
return;
}
if (!(p->lchild == NULL && p->rchild == NULL))
{
cout << p->data << " ";
}
ParentNodeShow(p->lchild);
ParentNodeShow(p->rchild);
}
void LeafNodeShow(RTreeNode* p)
{
if (p == NULL)
{
return;
}
if (p->lchild == NULL && p->rchild == NULL)
{
cout << p->data << " ";
}
LeafNodeShow(p->lchild);
LeafNodeShow(p->rchild);
}
void Preorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
cout << p->data << " ";
Preorder(p->lchild);
Preorder(p->rchild);
}
void Inorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
Preorder(p->lchild);
cout << p->data << " ";
Preorder(p->rchild);
}
void Postorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
Preorder(p->lchild);
Preorder(p->rchild);
cout << p->data << " ";
}
int main()
{
RTreeNode* root;
cout << "Please input root node : " << endl;
root = CreateTree();
cout << "Preorder :" << endl;
Preorder(root);
cout << endl;
cout << "Inorder :" << endl;
Inorder(root);
cout << endl;
cout << "Postorder :" << endl;
Postorder(root);
cout << endl;
cout << "There are " << ParentNode(root) << " parents" << endl;
cout << "Show Parents:" << endl;
ParentNodeShow(root);
cout << endl;
cout << "There are " << LeafNode(root) << " children" << endl;
cout << "Show Children:" << endl;
LeafNodeShow(root);
return 0;
}