画出下面代码的程序流程图
#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;
}
一样地画,递归就是调用函数而已。
当然,递归算法用流程图来表示是否直观,就见仁见智了。
假如输入的数字为1-9,要求输出的为这个九宫格的第一行和第一列。
#include<stdio.h>
//1 2 3 4 5 6 7 8 9
int main()
{
int a[9]={0};
int i,j,k,b[3][3]={0};
printf("请输入九个数字,用空格隔开:\n");
for(i=0;i<9;i++)
{
scanf("%d",&a[i]);
if(i%3==0)
{
printf("\n");
}
printf("%d ",a[i]);
}
printf("\n");
for(i=0;i<9;i++)
{
b[i/3][i%3]=a[i]; //将一位数组转三维数组
}
printf("输出结果为:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==1 ||j==1)//i行和j列
{
printf("%d ",b[i][j]); //%d后面加空格 打印时也会加空格的
}
else
{
printf("%c ",' ');//其他位置使用空格代替
}
}
printf("\n");//执行完一行输入回车符
}
return 0;
}
我可以使用 Microsoft Visio 绘制流程图来画出含有递归算法的C语言代码流程。具体步骤如下:
然后根据上述步骤,我尝试使用Microsoft Visio绘制了C语言递归算法的流程图,具体如下:
如果以上流程图无法展示,请点击这里查看:https://cdn.luogu.com.cn/upload/image_hosting/ma7bwh7i.png。