#include
#include
#define MAX 10001
// 树节点
typedef struct node
{
char k;
struct node *lchild;
struct node *rchild;
} Node;
int max(int m, int n)
{
if (m > n)
return m;
else
return n;
}
// 获取二叉树的高度
int TreeHeight(Node *root)
{
if (root == NULL)
return 0;
else
return 1 + max(TreeHeight(root->lchild), TreeHeight(root->rchild));
}
// 建立二叉树
Node *BuildTree(char *tree)
{
Node *root, *newnode, *stack[MAX];
int i = 0, top = -1, flag = 0;
root = newnode = NULL;
while(tree != '\0')
{
switch(tree)
{
case '(':
top ++;
stack[top] = newnode;
flag = 0;
break;
case ')':
top --;
break;
case ',':
flag = 1;
break;
default:
newnode = (Node *)malloc(sizeof(Node));
newnode->k = tree;
newnode->lchild = newnode->rchild = NULL;
if (root == NULL)
root = newnode;
else {
if (!flag)
stack[top]->lchild = newnode;
else
stack[top]->rchild = newnode;
}
break;
}
i++;
}
return root;
}
// 释放二叉树
void DestroyTree(Node *root)
{
if (root == NULL)
return ;
else {
DestroyTree(root->lchild);
DestroyTree(root->rchild);
free(root);
}
}
int main()
{
char tree[MAX];
Node *root = NULL;
printf("Input B Tree = ");
scanf("%s", tree);
root = BuildTree(tree);
printf("Tree Height = %d\n", TreeHeight(root));
DestroyTree(root);
return 0;
}
绝对可以运行! |