二叉树
#include <stdio.h> #include <stdlib.h> // 二叉树节点的定义 typedef struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 创建新节点 TreeNode* createNode(int data) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); if (newNode == NULL) { printf("内存分配失败\n"); exit(EXIT_FAILURE); } newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } // 插入节点到二叉搜索树 TreeNode* insert(TreeNode* root, int data) { if (root == NULL) { return createNode(data); } if (data < root->data) { root->left = insert(root->left, data); } else if (data > root->data) { root->right = insert(root->right, data); } return root; } // 先序遍历 void preOrderTraversal(TreeNode* root) { if (root != NULL) { printf("%d ", root->data); preOrderTraversal(root->left); preOrderTraversal(root->right); } } // 中序遍历 void inOrderTraversal(TreeNode* root) { if (root != NULL) { inOrderTraversal(root->left); printf("%d ", root->data); inOrderTraversal(root->right); } } // 后序遍历 void postOrderTraversal(TreeNode* root) { if (root != NULL) { postOrderTraversal(root->left); postOrderTraversal(root->right); printf("%d ", root->data); } } // 求二叉树的叶子数 int getLeafCount(TreeNode* root) { if (root == NULL) { return 0; } if (root->left == NULL && root->right == NULL) { return 1; // 叶子节点 } return getLeafCount(root->left) + getLeafCount(root->right); } // 求二叉树的深度 int getTreeDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = getTreeDepth(root->left); int rightDepth = getTreeDepth(root->right); return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1); } // 求二叉树中度为一的节点个数 int getDegreeOneCount(TreeNode* root) { if (root == NULL) { return 0; } int degreeOneCount = 0; if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL)) { // 度为一的节点 degreeOneCount = 1; } degreeOneCount += getDegreeOneCount(root->left); degreeOneCount += getDegreeOneCount(root->right); return degreeOneCount; } // 销毁二叉树 void destroyTree(TreeNode* root) { if (root != NULL) { destroyTree(root->left); destroyTree(root->right); free(root); } } int main() { TreeNode* root = NULL; // 插入节点 root = insert(root, 5); root = insert(root, 3); root = insert(root, 7); root = insert(root, 2); root = insert(root, 4); // 先序遍历 printf("先序遍历结果:"); preOrderTraversal(root); printf("\n"); // 中序遍历 printf("中序遍历结果:"); inOrderTraversal(root); printf("\n"); // 后序遍历 printf("后序遍历结果:"); postOrderTraversal(root); printf("\n"); // 求叶子数 int leafCount = getLeafCount(root); printf("叶子数:%d\n", leafCount); // 求深度 int depth = getTreeDepth(root); printf("树的深度:%d\n", depth); // 求度为一的节点个数 int degreeOneCount = getDegreeOneCount(root); printf("度为一的节点个数:%d\n", degreeOneCount); // 销毁二叉树 destroyTree(root); return 0; }