我的C代码不起作用,它与二叉树有关

问题描述 投票:0回答:1

我想用 C 语言设计一个函数,它以二叉树作为输入,并确定二叉树是否围绕其中心对称。它不允许我正确输入数据。在

main
函数中,它不会接受请求的输入,并且在执行时不会询问右侧输入。

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// Structure for binary tree node
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

// Function to create a new binary tree node from a given data.
struct Node *newNode(int data) {
    struct Node *node = (struct Node *)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Helper function to check if two subtrees are mirror images of each other.
bool isMirror(struct Node *leftSubtree, struct Node *rightSubtree) {
    if (leftSubtree == NULL && rightSubtree == NULL)
        return true;
    if (leftSubtree == NULL || rightSubtree == NULL)
        return false;
    
    return (leftSubtree->data == rightSubtree->data) &&
           isMirror(leftSubtree->left, rightSubtree->right) &&
           isMirror(leftSubtree->right, rightSubtree->left);
}

// Function to determine if the tree is symmetric.
bool isSymmetric(struct Node *root) {
    if (root == NULL)
        return true;
    
    return isMirror(root->left, root->right);
}

// Function to build a binary tree based on user input.
struct Node *buildTree() {
    int data;
    printf("Enter data (-1 for NULL): ");
    scanf("%d", &data);
    
    if (data == -1)
        return NULL;
    
    struct Node *newNodePtr = newNode(data);
    printf("Enter left child of %d:\n", data);
    newNodePtr->left = buildTree();
    printf("Enter right child of %d:\n", data);
    newNodePtr->right = buildTree();
    
    return newNodePtr;
}

int main() {
    struct Node *root = NULL;
    printf("Enter the root data:\n");
    root = buildTree();

    if (isSymmetric(root))
        printf("The binary tree is symmetric.\n");
    else
        printf("The binary tree is not symmetric.\n");

    return 0;
}
c data-structures binary-tree
1个回答
0
投票

代码似乎不能归咎于您所描述的问题,但是

buildTree()
中存在一个问题:您没有检查
scanf("%d", &data)
的返回值。如果
scanf
成功将输入转换为整数,它将返回
1
,否则可能会返回
0
EOF
并且
data
的值可能仍然未初始化或不确定。您应该测试是否成功并报告错误或将
EOF
视为输入结束,因此所有剩余节点应为空。


// Function to build a binary tree based on user input.
struct Node *buildTree(void) {
    int data;

    printf("Enter data (-1 for NULL): ");
    switch (scanf("%d", &data)) {
      case EOF:
        return NULL;
      case 0:
        printf("invalid input\n");
        exit(1);
      case 1:
        if (data == -1)
          return NULL;
        break;
    }
    struct Node *newNodePtr = newNode(data);
    printf("Enter left child of %d:\n", data);
    newNodePtr->left = buildTree();
    printf("Enter right child of %d:\n", data);
    newNodePtr->right = buildTree();
    return newNodePtr;
}
© www.soinside.com 2019 - 2024. All rights reserved.