打印出' 0'对于每个左子树遍历和' 1'对于每个右边的子树遍历

时间:2014-08-05 07:01:08

标签: c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define n 5

struct node
{
    int num;
    struct node *left;
    struct node *right;
}*root_ptr, *current, *previous, *newNode;

void getCodes(struct node *);

char *symbols[] = {"A", "B", "C", "D", "E"}, **p=symbols;
char codeKeeper[32]={0}, *code_ptr = codeKeeper;

int main(int argc, char *argv[])
{
    //some code

    //tree structure formation
    getCodes(root_ptr);
    return 0;
}
void getCodes(struct node *no)
{
    if(no!=NULL)
    {
        *code_ptr++ = '0';
        getCodes(no->left);
        if(no->left==NULL)
            printf("%d left child is %s having code as %s0\n", no->num, *p++, codeKeeper+1);
        if(no->right==NULL)
            printf("%d right child is %s having code as %s1\n", no->num, *p++, codeKeeper+1);
        *(--code_ptr) = '1';
        getCodes(no->right);
    }
}

形成的树

            2
    1               3
                           4

我想要做的是打印一个&#39; 0&#39;对于每个左分支遍历和&#39; 1&#39;对于每个右分支遍历,所以我使用按顺序遍历。此外,当我按顺序遍历时,它必须检查每个节点是否没有左子树或右子树或两者,并相应地从左到右打印出符号(带有0和1),填充NULL指针时和遇到。

我的getCodes()函数只能从右边打印出两个字符..上面的树深度及其代码被吃掉或者没有填充。

编辑: 符号&#34; A&#34;必须留下1的孩子,符号&#34; B&#34;必须是1的正确的孩子..像这样,必须在遍历时动态识别树叶

所以最终的树可以被认为是

               2
        1                3
A            B        C         4
                             D       E

因此,A的输出为00,B为01,C为10,D为110,E为111 从上面的树的外观..你可以看到A,B,C,D,E已经为叶子中的每个NULL指针从左到右线性地放置

这是我从getCodes()函数

获得的
1 left child is A having code as 00
1 right child is B having code as 01
3 left child is C having code as 10
4 left child is D having code as 10
4 right child is E having code as 11

1 个答案:

答案 0 :(得分:1)

void inorder(char string[20],int index,tree *root)//index is sent 0 from main
{
  if(root)
  {
    string[index]='0';
    string[index+1]='\0';
    inorder(string,index+1,root->left);//Add 0 at end when you go to left
    printf("%s\n",string);
    string[index]='1';
    string[index]='\0';
    inorder(string,index+1,root->right);//Add 1 at end when you go to right
  }
}