CCI_Q4.1

本文参考该作者文章当作编程笔记:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

Q:

实现一个函数检查一棵树是否平衡。对于这个问题而言, 平衡指的是这棵树任意两个叶子结点到根结点的距离之差不大于1。

思路:

找这棵树的最高层max,和最低层min,比较下即可。

CODE:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<limits.h>
 4 #define N 6
 5 #define key(A) (A)
 6 #define less(A,B) (A<B)
 7 typedef struct node
 8 {
 9     char item;
10     struct node *l,*r;
11 }node;
12 void insertNode(node **h,char item)
13 {
14     if((*h)==NULL)
15     {
16         *h=(node *)malloc(sizeof(node));
17         (*h)->item=item;
18         (*h)->l=NULL;
19         (*h)->r=NULL;
20         return;
21     }
22     if(item<(*h)->item)
23         insertNode(&((*h)->l),item);
24     else
25         insertNode(&((*h)->r),item);
26 }
27 void printfNode(char item,int blank)
28 {
29     int i;
30     for(i=0;i<blank;++i)
31         printf(" ");
32     printf("%c\n",item);
33 }
34 void traversePre(node *h,int blank)
35 {
36     if(h==NULL)
37     {printfNode('*',blank); return;}
38     printfNode(h->item,blank);
39     traversePre(h->l,blank+1);
40     traversePre(h->r,blank+1);
41 }
42 int max=INT_MIN,min=INT_MAX,hight=-1;
43 /*根节点为第0层,当到达叶子节点时,判断是否为最大、最小高度*/
44 void traversePreMaxMin(node *h)
45 {
46     if(h==NULL)
47         return;
48     ++hight;
49     traversePreMaxMin(h->l);
50     traversePreMaxMin(h->r);
51     if(h->l==NULL && h->r==NULL)
52     {
53         if(max<hight)
54             max=hight;
55         if(min>hight)
56             min=hight;
57     }
58     --hight;
59 }
60 int main()
61 {
62     node *head=NULL;
63     char s[]="HEYCFA";
64     int i;
65     for(i=0;i<N;++i)
66         insertNode(&head,s[i]);
67     traversePre(head,0);    /*前序遍历树*/
68     printf("%d\t%d\n",max,min);    /*max和min初始值*/
69     traversePreMaxMin(head);    /*找出树的最大、最小高度*/
70     printf("%d\t%d\n",max,min);    /*输出最大、最小高度*/
71     return 0;
72 }
View Code

 

posted @ 2014-03-19 14:31  哈士奇.银桑  阅读(91)  评论(0)    收藏  举报