树的数据结构是基本功,但是确实很难,重点在于对于递归这种思想的把握,通过建树求树高,可以深入理解递归的思想。
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
char data;
struct Node *left;
struct Node *right;
}TreeNode;
TreeNode *Creat_Tree()
{
TreeNode *node;
char ch;
scanf("%c",&ch);
if (ch == '#')
node = NULL;
else
{
node = (TreeNode*)malloc(sizeof(node));
node->data = ch;
node->left = Creat_Tree();
node->right = Creat_Tree();
}
return node;
}
int Tree_Height(TreeNode *root)
{
int dep1 = 0;
int dep2 = 0;
if (!root)
return 0;
else
{
dep1 = Tree_Height(root->left);
dep2 = Tree_Height(root->right);
return (dep1>dep2)?dep1+1:dep2+1;
}
}
void order(TreeNode *node)
{
if (node != NULL)
{
printf("%c ",node->data);
order(node->left);
order(node->right);
}
}
int main()
{
TreeNode *root;
printf("请按先序遍历顺序输入数据,叶子节点用#表示\n");
root = Creat_Tree();
printf("先序遍历:\n");
order(root);
int h = 0;
printf("\n");
h = Tree_Height(root);
printf("%d\n",h);
return 0;
}