#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;
}