首页 > 其他分享 >顺序构造二叉树

顺序构造二叉树

时间:2023-02-20 13:57:41浏览次数:35  
标签:顺序 TreeNode struct val 构造 right 二叉树 root

基于链表存储按输入顺序构造的二叉树,输入为-1时结束

#include <stdio.h>
#include <stdlib.h>
 
struct TreeNode {
    int val;
    struct TreeNode *left,*right;
};
 
struct TreeNode a[520];
 
struct TreeNode* Creat(struct TreeNode* root)
{
    int k=0,i,j,n;
    while(scanf("%d",&n),n!=-1)
        a[k++].val=n;
    for(i=0,j=1;i<k;i++,j++)
    {
        if(i+j>=k||a[i+j].val==0) a[i].left=NULL;
        else a[i].left=&a[i+j];
        if(i+j+1>=k||a[i+j+1].val==0) a[i].right=NULL;
        else a[i].right=&a[i+j+1];
    }
    return &a[0];
}
int main()
{
    struct TreeNode* root=NULL;
    root=Creat(root);
    return 0;
}

 

标签:顺序,TreeNode,struct,val,构造,right,二叉树,root
From: https://www.cnblogs.com/jyssh/p/17137080.html

相关文章