啦啦啦啦啦啦

#include <stdio.h>

#include <stdlib.h>


typedef struct TreeNode {

    char data;

    struct TreeNode* left;

    struct TreeNode* right;

} TreeNode;


// 创建二叉树

TreeNode* createTree() {

    char value;

    scanf(" %c", &value);

    if (value == '#') {

        return NULL;

    }

    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));

    root->data = value;

    root->left = createTree();

    root->right = createTree();

    return root;

}


// 计算二叉树结点总数

int countNodes(TreeNode* root) {

    int count = 0;

    TreeNode* curr = root;

    int stackTop = -1;

    TreeNode* stack[1000];


    while (1) {

        while (curr != NULL) {

            stack[++stackTop] = curr;

            curr = curr->left;

        }

        if (stackTop == -1) {

            break;

        }

        curr = stack[stackTop--];

        count++;

        curr = curr->right;

    }


    return count;

}


// 计算二叉树叶子总数

int countLeaves(TreeNode* root) {

    int count = 0;

    TreeNode* curr = root;

    int stackTop = -1;

    TreeNode* stack[1000];


    while (1) {

        while (curr != NULL) {

            stack[++stackTop] = curr;

            curr = curr->left;

        }

        if (stackTop == -1) {

            break;

        }

        curr = stack[stackTop--];

        if (curr->left == NULL && curr->right == NULL) {

            count++;

        }

        curr = curr->right;

    }


    return count;

}


// 计算二叉树高度

int getHeight(TreeNode* root) {

    int height = 0;

    TreeNode* curr = root;

    int stackTop = -1;

    int heightStack[1000];

    TreeNode* stack[1000];


    while (1) {

        while (curr != NULL) {

            stack[++stackTop] = curr;

            heightStack[stackTop] = height;

            height++;

            curr = curr->left;

        }

        if (stackTop == -1) {

            break;

        }

        curr = stack[stackTop--];

        height = heightStack[stackTop + 1];

        if (height > heightStack[stackTop]) {

            heightStack[stackTop] = height;

        }

        curr = curr->right;

    }


    return heightStack[0];

}


int main() {

    printf("请输入二叉树的数据(先序遍历,用#表示空结点):\n");

    TreeNode* root = createTree();

    printf("二叉树结点总数:%d\n", countNodes(root));

    printf("二叉树叶子总数:%d\n", countLeaves(root));

    printf("二叉树高度:%d\n", getHeight(root));

    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值