You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.3 KiB

#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
void (*func)(struct TreeNode *); // 节点的函数
struct TreeNode *left; // 左子节点
struct TreeNode *right; // 右子节点
} TreeNode;
void nodeFunction(TreeNode *node) {
printf("Node function executed: %p\n", (void *)node);
}
void leafFunction(TreeNode *node) {
printf("Leaf function executed: %p\n", (void *)node);
}
TreeNode *createBinaryTree(int depth) {
if (depth == 0) return NULL;
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->func = (depth > 1) ? nodeFunction : leafFunction; // 叶节点使用 leafFunction
node->left = createBinaryTree(depth - 1);
node->right = createBinaryTree(depth - 1);
return node;
}
void executeTree(TreeNode *node) {
if (node == NULL) return;
// 首先递归执行左右子节点
executeTree(node->left);
executeTree(node->right);
// 然后执行当前节点的函数
node->func(node);
}
void freeTree(TreeNode *node) {
if (node == NULL) return;
freeTree(node->left);
freeTree(node->right);
free(node);
}
int main() {
// 创建一个深度为 3 的二叉树
TreeNode *root = createBinaryTree(3);
// 执行二叉树
executeTree(root);
// 释放二叉树占用的内存
freeTree(root);
return 0;
}