#include<iostream>
#include<stack>
#include<queue>
using namespace std;
struct node
{
char data;
char tag;
node* left, * right;
};
typedef node* list;
list BuildTreeByLists(string cnt)
{
stack<list>s;
list temp = NULL;
list rootnode = NULL;
int i = 0, k = 1;
while (i < cnt.length())
{
switch (cnt[i])
{
case '(':
if (temp != NULL)
s.push(temp);
k = 1;
break;
case ',':
k = 2;
break;
case ')':
s.pop();
break;
default:
temp = new node;
temp->data = cnt[i];
temp->left = temp->right = NULL;
if (rootnode == NULL)
{
rootnode = temp;
}
else
{
if (k == 1)
s.top()->left = temp;
else
s.top()->right = temp;
}
}
i++;
}
return rootnode;
}
int getNodeCount(list node)
{
if (node == NULL) return 0;
else return 1 + getNodeCount(node->left) + getNodeCount(node->right);
}
int getHeight(list node)
{
if (node == NULL) return 0;
else
{
int leftHeight = getHeight(node->left);
int rightHeight = getHeight(node->right);
if (leftHeight < rightHeight)
return rightHeight + 1;
else
return leftHeight + 1;
}
}
void preOrderTraverse(list node) {
if (node != NULL) {
printf("%c", node->data);
preOrderTraverse(node->left);
preOrderTraverse(node->right);
}
}
void printList(list node)
{
if (node != NULL)
{
cout << node->data;
if (node->left != NULL || node->right != NULL)
{
cout << "(";
if (node->left != NULL)
printList(node->left);
cout << ",";
if (node->right != NULL)
printList(node->right);
cout << ")";
}
}
}
void preOrderNorecursion(list root)
{
cout << endl;
stack<list>s;
s.push(NULL);
list p = root;
while (p!=NULL)
{
cout << p->data;
if (p->right)
s.push(p->right);
if (p->left)
p = p->left;
else
{
p = s.top();
s.pop();
}
}
}
void levelOrder(list root)
{
cout << endl;
queue<list>q;
list p = root;
q.push(p);
while (!q.empty())
{
p = q.front(); q.pop();
cout << p->data;
if (p->left)q.push(p->left);
if (p->right)q.push(p->right);
}
}
void inOrderNorecurison(list root)
{
cout << endl;
stack<list>s;
list p = root;
do
{
while (p != NULL)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top(); s.pop();
cout << p->data;
p = p->right;
}
} while (p != NULL || !s.empty());
}
void postOrderNorecurison(list root)
{
cout << endl;
list p = root;
stack<list>s;
do {
while (p != NULL)
{
p->tag = 'l';
s.push(p);
p = p->left;
}
int flag = 1;
while (flag&&!s.empty())
{
p = s.top(); s.pop();
if (p->tag == 'l')
{
p->tag = 'r';
s.push(p);
p = p->right;
flag = 0;
}
else if(p->tag=='r')
cout << p->data;
}
} while (!s.empty());
}
int main()
{
string s = "1(2(3,4(5,)),6(,7))";
list root=BuildTreeByLists(s);
preOrderTraverse(root);
preOrderNorecursion(root);
levelOrder(root);
inOrderNorecurison(root);
postOrderNorecurison(root);
cout << endl;
cout << "树的结点个数为" << getNodeCount(root) << endl;
cout << "树的高度为"<<getHeight(root) << endl;
printList(root);
}