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

时间:2017-11-09 13:29:22

标签: c

我遇到了部分代码。 我应该接受所有我必须放在二叉树中并对它们进行排序的元素,这样工作正常,如果我采用例如6,5,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;

}

1 个答案:

答案 0 :(得分: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);

这不是最好的方法,它可以自己优化,一般来说,执行迭代顺序遍历更好。您可以找到一个here的示例。要点是:

  

1)创建一个空堆栈。

     

2)以root身份初始化当前节点

     

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

     

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

     
    

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

         

b)打印弹出的项目,设置current = popped_item-&gt; right

         

c)转到第3步。

  
     

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