二叉树的基本运算

    由str创建二叉链

    1. {
    2. BTNode *St[MaxSize],*p=NULL;
    3. int top=-1,k,j=0;
    4. char ch;
    5. bt=NULL; /*建立的二叉树初始时为空*/
    6. ch=str[j];
    7. while (ch!='\0') /*str未扫描完时循环*/
    8. {
    9. switch(ch)
    10. {
    11. case '(':top++;St[top]=p;k=1; break; /*为左孩子结点*/
    12. case ')':top--;break;
    13. case ',':k=2; break; /*为孩子结点右结点*/
    14. default:p=(BTNode *)malloc(sizeof(BTNode));
    15. p->data=ch;p->lchild=p->rchild=NULL;
    16. bt=p;
    17. else /*已建立二叉树根结点*/
    18. { switch(k)
    19. {
    20. case 1:St[top]->lchild=p;break;
    21. }
    22. }
    23. }
    24. j++;
    25. ch=str[j];
    26. }
    27. }

    求二叉树的结点个数

    1. int NodeCount(BTNode *bt) /*求二叉树bt的结点个数*/
    2. {
    3. int num1,num2;
    4. if (bt==NULL) /*空树结点个数为0*/
    5. return 0;
    6. else
    7. { num1=NodeCount(bt->lchild); /*求出左子树的结点数*/
    8. num2=NodeCount(bt->rchild); /*求出右子树的结点数*/
    9. return (num1+num2+1);
    10. }
    11. }

    以括号表示法输出二叉树

    1. {
    2. if (bt!=NULL)
    3. printf("%c",bt->data);
    4. if (bt->lchild!=NULL || bt->rchild!=NULL)
    5. {
    6. printf("(");
    7. DispBTree(bt->lchild); /*递归处理左子树*/
    8. if (bt->rchild!=NULL)
    9. printf(",");
    10. DispBTree(bt->rchild); /*递归处理右子树*/
    11. printf(")");
    12. }
    13. }
    14. }

    main

    1. void main()
    2. {
    3. BTNode *bt;
    4. CreateBTree(bt,"A(B(D,E(G,H)),C(,F(I)))"); /*构造图5.10(a)所示的二叉树*/
    5. printf("二叉树bt:");DispBTree(bt);printf("\n");
    6. printf("bt的高度:%d\n",BTHeight(bt));
    7. printf("bt的结点数:%d\n",NodeCount(bt));
    8. printf("bt的叶子结点数:%d\n",LeafCount(bt));
    9. printf("bt凹入表示:\n");DispBTree1(bt);printf("\n");