繁体   English   中英

C语言-具有递归功能的二叉树,打印“节点连接”

[英]C language - Binary tree with recursive function, printing “node connection”

我陷入了我的代码的一部分。 我应该将所有必须放入二叉树中并对其进行排序的元素都接受,并且工作正常,如果我以6,5,4,4,3,2,1为例,它将3打印为root,然后是1、2、4、5和6,因为递归函数应该是这样工作的(必须使用代码中提到的函数),这是正确的。 我的问题是我不确定如何使用指针以及打印“连接”的指针。 例如,这样的话就足够了:节点-3,父母-无,孩子-1和5节点-5,父母-3,孩子-4和6

我愿意接受所有想法。

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


typedef struct _node
{
int data;
struct _node *left;
struct _node *right;

}node;

node* newnode(int a)
{
node *p;

p=(node*)malloc(sizeof(node));

p->data = a;

printf("%d\n", p->data);

p->left = NULL;
p->right = NULL;

return p;
};

void MakeBalTree(int *x, int left, int right)
{
int middle;

if (left <= right)
{
    middle = (left + right)/2;
    newnode(x[middle]);
}

if(left>right)
    return;

MakeBalTree (x, left, middle-1);
MakeBalTree (x, middle+1, right);
}

void sort(int *x, int count)
{
int i, j, tmp;

for (i = 0; i < count - 1; i++)
{
    for (j = i + 1; j < count; j++)
    {
        if (x[i] > x[j])
        {
            tmp = x[i];
            x[i] = x[j];
            x[j] = tmp;
        }
    }
}
}

int main()
{
int i, j;
int count = 0;
int *x = NULL;
char c;

do{
    printf("Enter a number:");
    scanf("%d", &i);
    count++;

    x = (int*)realloc(x, count * sizeof(int));
    x[count-1]=i;

    printf("Enter more numbers (y/n)? \n");
    scanf(" %c", &c);

    if(c=='y')
        continue;
    if(c=='n')
        sort(x, count);
    else while(c != 'y' && c !='n')
    {
        printf("Wrong character, please enter again:");
        scanf(" %c", &c);
    }
}while(c=='y');

MakeBalTree(x, 0, count-1);

free(x);

return 0;

}

忽略排序等所有其他内容。打印二叉树的方法是遍历树,并在向下移动时打印每个节点。 最简单的方法是使用递归。 例如

void printTree (node* root, node* parent)
{
    if (parent == NULL) {
        printf("Node - %d, parent - none, children ", root->data);
    } else {
        printf("Node - %d, parent - %d, children ", root->data, parent->data);
    }
    if (root->left != NULL && root->right != NULL) {
        printf("%d and %d\n", root->right->data, root->left->data);
    } else if (root->left == NULL && root->right != NULL) {
        printf("%d\n", root->right->data);
    } else if (root->left != NULL && root->right == NULL) {
        printf("%d\n", root->left->data);
    } else {
        printf("none\n");
    }

    if (root->left != NULL)
        printTree(root->left, root);
    if (root->right != NULL)
        printTree(root->right, root);
}

// Calling
printTree(&root, NULL);

这不是最好的方法,它本身可以进行优化,通常最好执行迭代的有序遍历。 您可以在这里找到一个示例。 要点是:

1)创建一个空堆栈S。

2)初始化当前节点为根

3)将当前节点推到S并设置current = current-> left,直到current为NULL

4)如果current为NULL并且堆栈不为空,则

a)从堆栈中弹出顶层项目。

b)打印弹出的项目,将当前设置为popped_item-> right

c)转到步骤3。

5)如果current为NULL并且堆栈为空,那么我们就完成了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM