画出下面代码的程序流程图
#include <stdio.h>
#include <stdlib.h>
// Binary tree node structure
struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
};
// Create a new node
struct TreeNode* createNode(char data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Build the binary tree
struct TreeNode* buildTree() {
char data;
printf("Enter node value (or . for NULL): ");
scanf(" %c", &data);
if (data == '.')
return NULL;
struct TreeNode* root = createNode(data);
printf("Enter left child of %c:\n", data);
root->left = buildTree();
printf("Enter right child of %c:\n", data);
root->right = buildTree();
return root;
}
// Perform post-order traversal of the binary tree
void postOrderTraversal(struct TreeNode* root) {
if (root == NULL)
return;
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%c ", root->data);
}
// Find the path to a specified node
int findNodePath(struct TreeNode* root, char target, char path[], int level) {
int i;
if (root == NULL)
return 0;
// Add the current node to the path
path[level] = root->data;
// Found the target node
if (root->data == target) {
// Print the path
printf("Path to node %c: ", target);
for ( i = 0; i <= level; i++) {
printf("%c ", path[i]);
}
printf("\n");
return 1;
}
// Search for the target node in the left or right subtree
if (findNodePath(root->left, target, path, level + 1) || findNodePath(root->right, target, path, level + 1))
return 1;
// If the current node is not in the path, remove it
path[level] = '\0';
return 0;
}
int main() {
// Build the binary tree
printf("Build the binary tree:\n");
struct TreeNode* root = buildTree();
// Perform post-order traversal of the binary tree
printf("Post-order Traversal: ");
postOrderTraversal(root);
printf("\n");
// Find the path to a specified node
char path[100]; // Assume the path does not exceed 100 nodes
char target;
printf("Enter the target node value: ");
scanf(" %c", &target);
findNodePath(root, target, path, 0);
return 0;
}