普通树(双亲表示法存储)转二叉树【左孩子右兄弟表示法】

本文对普通树采用顺序存储结构

普通树(双亲表示法存储)转二叉树【左孩子右兄弟表示法】_第1张图片

 图片来源:https://blog.csdn.net/weixin_44162361/article/details/118994573?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%A0%91%20%E8%96%9B%E5%AE%9A%E8%B0%94%E7%9A%84%E7%8C%AB&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-3-118994573.142^v42^pc_rank_34,185^v2^control&spm=1018.2226.3001.4449icon-default.png?t=M7J4https://blog.csdn.net/weixin_44162361/article/details/118994573?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%A0%91%20%E8%96%9B%E5%AE%9A%E8%B0%94%E7%9A%84%E7%8C%AB&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-3-118994573.142^v42^pc_rank_34,185^v2^control&spm=1018.2226.3001.4449

输入格式:

普通树(双亲表示法存储)转二叉树【左孩子右兄弟表示法】_第2张图片 

 图片来源:

https://blog.csdn.net/weixin_44162361/article/details/118994573?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%A0%91%20%E8%96%9B%E5%AE%9A%E8%B0%94%E7%9A%84%E7%8C%AB&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-3-118994573.142^v42^pc_rank_34,185^v2^control&spm=1018.2226.3001.4449icon-default.png?t=M7J4https://blog.csdn.net/weixin_44162361/article/details/118994573?ops_request_misc=&request_id=&biz_id=102&utm_term=%E6%A0%91%20%E8%96%9B%E5%AE%9A%E8%B0%94%E7%9A%84%E7%8C%AB&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-3-118994573.142^v42^pc_rank_34,185^v2^control&spm=1018.2226.3001.4449

以下为普通树转二叉树完整代码:

#include
#include

#define MaxSize 50

typedef struct TreeNode
{
    char data;
    struct TreeNode* left_firstchild;
    struct TreeNode* nextsibiling;
}TreeNode,*BinTreeNode;


typedef struct
{
    char data;
    int parent;
}NorTreeNode;

BinTreeNode ConstructTree(NorTreeNode* p,int num)
{
    BinTreeNode Root,cur_node;
    Root = NULL;    // 根节点
    TreeNode* brr[num];     // 指针数组,存放节点
    for(int j=0;jdata = p[j].data;     // 复制data
        cur_node->left_firstchild = cur_node->nextsibiling = NULL;
        brr[j] = cur_node;      // 将节点指针存入数组
        if(Root == NULL) { Root = cur_node; }
    }
    for(int i=0;ileft_firstchild = brr[k];   // 父节点连接孩子节点
                break;
            }
        }
        //   寻找第一个兄弟节点
        for(int k=i+1;knextsibiling = brr[k];  // 连接兄弟节点
                break;
            }
        }

    }


    return Root;
}

void PreorderVisit(BinTreeNode RooT)
{
    if(RooT != NULL)
    {
        printf("%c",RooT->data);
        PreorderVisit(RooT->left_firstchild);
        PreorderVisit(RooT->nextsibiling);
    }

}
int main()
{
    NorTreeNode arr[MaxSize];
    BinTreeNode root;
    int n;
    printf("Number of nodes: \n");
    scanf("%d",&n);
    getchar();  // 接收回车键
    for(int i=0;i

 该代码在Code::Blocks 20.03中测试通过

普通树(双亲表示法存储)转二叉树【左孩子右兄弟表示法】_第3张图片

如有错误,恳请各位批评指正!

你可能感兴趣的:(C语言,二叉树,c语言)