C 语言源码:二叉树求宽度与深度

C 语言 二叉树 求宽度与深度

图片

源码如下:

#include <stdio.h>#include <stdlib.h>
typedef struct Tree {    char ch;    struct Tree *left;    struct Tree *right;} Tree;
typedef struct queNode {    Tree *p;    int lno; //层号信息} queNode;
//求宽度void GetMaxHW(Tree *root){    queNode Q[100];    Tree *q = NULL;    int frontQ = 0, rearQ = 0;    int Lno;    if (!root) return;
    Q[++rearQ].p = root;    Q[rearQ].lno = 1;
    while(frontQ != rearQ) {        q = Q[++frontQ].p;        Lno = Q[frontQ].lno;        if (q->left != NULL) {            Q[++rearQ].p = q->left;            Q[rearQ].lno = Lno + 1;        }        if (q->right != NULL) {            Q[++rearQ].p = q->right;            Q[rearQ].lno = Lno + 1;        }    }// Lno 为深度
    int width = 0;    for (int i = 1; i <= Lno; i++) {        int num = 0;        for (int j = 1; j <= rearQ; j++) {            if(Q[j].lno == i) {                num++;            }        }        if (num > width) {            width = num;        }    }
    printf("height = %d, width = %d\n", Lno, width);}
Tree *newNode(char ch){    Tree *t = (Tree *)malloc(sizeof(Tree));    t->ch = ch;    t->left = t->right = NULL;    return t;}
Tree *create(){    char ch;    ch = getchar();    Tree *node = NULL;    if (ch == '#') {        node = NULL;    } else {        node = newNode(ch);        node->left = create();        node->right = create();    }    return node;}
void preOrder(Tree *root){    if (root) {        printf("%c ", root->ch);        preOrder(root->left);        preOrder(root->right);    }}
void inOrder(Tree *root){    if (root) {        inOrder(root->left);        printf("%c ", root->ch);        inOrder(root->right);    }}
void postOrder(Tree *root){    if (root) {        postOrder(root->left);        postOrder(root->right);        printf("%c ", root->ch);    }}

int main(){    Tree *root = create();    printf("preOrder: "); preOrder(root);    printf("\n");    printf("inOrder: "); inOrder(root);    printf("\n");    printf("postOrder: "); postOrder(root);    printf("\n");    GetMaxHW(root);    printf("\n");    return 0;}

编译,运行:

[root@localhost tree]# ./TreeHW ABC##D##E#F##preOrder: A B C D E F inOrder: C B D A E F postOrder: C D B F E A height = 3, width = 3
THE END