【问题标题】:getting binary tree node获取二叉树节点
【发布时间】:2018-11-25 04:10:49
【问题描述】:

我使用堆栈进行了非递归后序。但在 Main 函数中,我想使用 scanf 获取 TreeNode,而不是手动键入所有 TreeNode。例如 printf("你想要多少个 TreeNode?");并获取 TreeNodes 的数量,然后 printf("enter TreeNodes");所以我像这样输入 1 2 3 4 5 。 如何编码?

#include <stdio.h>
#include <stdbool.h>
#define STACK_SIZE 10
typedef struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
}TreeNode;

typedef struct Stack {
    TreeNode *buf[STACK_SIZE];
    int top;
}Stack;


void postOrder(TreeNode *root, Stack *stack)
{
    Stack* s = stack;
    if (root == NULL) return;
    TreeNode* current = root;
    TreeNode *tmp;
    bool done = 0;
    InitStack(s);


    while(!done)
    {
        while (current != NULL)
        {
            if (current->right != NULL)
                Push(s, current->right);
            Push(s, current);
            current = current->left;
        }
        if (IsEmpty(s))
            break;
        current = Pop(s);
        if (IsEmpty(s))
        {
            printf("%d", current->data);
            break;
        }
        tmp = Pop(s);
        if (tmp == current->right)
        {
            Push(s, current);
            current = current->right;
        }
        else
        {
            printf("%d", current->data);
            Push(s, tmp);
            current = NULL;
        }
    }
}
int main()
{   
    Stack s;
    TreeNode one, two, three, four, five;

    one.data = 1;
    two.data = 2;
    three.data = 3;
    four.data = 4;
    five.data = 5;

    one.left = &two;        one.right = &three;
    two.left = &four;       two.right = &five;
    three.left = NULL;      three.right = NULL;
    four.left = NULL;       four.right = NULL;
    five.left = NULL;       five.right = NULL;

    postOrder(&one, &s);

    printf("\n");
    getchar();

    return 0;
}

【问题讨论】:

  • 您需要阅读有关动态内存分配的信息。你的 C 教科书应该有一章处理这个问题。

标签: c data-structures scanf binary-tree


【解决方案1】:

实现一个单独的方法来使用动态内存分配构造树。使用 malloc 函数分配内存。将新节点插入到树的适当位置。

void insertNode(TreeNode *root,int data){
        //To Do create node dynamically using malloc and attach to root at appropriate position
    }


读取输入的方法如下主函数所示:

int main()
{
    Stack s;
    TreeNode *rootNode = NULL;
    int nodeCount;
    int data;
    printf("Enter number of nodes:\n");
    scanf("%d",&nodeCount);
    printf("enter TreeNodes Data:\n");
    for (int i=0; i < nodeCount; i++) {
        scanf("%d",&data);
        insertNode(rootNode,data);
    }
    postOrder(rootNode, &s);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2018-07-10
    相关资源
    最近更新 更多