树<1>

最近做了看了些内核代码,感觉数据结构的知识还是不够,得加紧补习补习。

typedef struct node *tree_pointer;
struct node{
    int data;
    tree_pointer left_child;
    tree_pointer right_child;
};

1.树的相关概念

2.二叉树的前序,中序,后序遍历

前序遍历:

void preorder(tree_pointer temp)
{
    if(temp)
    {
         printf("%d",temp->data);
         preorder(temp->left_child);
         preorder(temp->right_child);
     }
}

中序遍历:

void inorder(tree_pointer temp)
{
    if(temp)
    {
        inorder(temp->left_child);
        printf("%d",temp->data);
        inorder(temp->right_child);
    }
}
后序遍历:
void postorder(tree_pointer temp)
{
    if(temp)
    {
           postorder(temp->left_child);
           postorder(temp->right_child);
           printf("%d",temp->data);
    }
}
3.二叉树的复制
tree_pointer copy(tree_pointer temp)
{
    tree_pointer f;
    f = (tree_pointer)malloc(sizeof(node));
    if(temp)
    {
        f->data = temp->data;
        f->left_child = copy(temp->left_child);
        f->right_child = copy(temp->right_child);
        return f;  
    }
    return NULL;
}
4.判断两个二叉树是否相等
int equal(tree_pointer first,tree_pointer second)
{
    return ((!first&&!second)||((first&&second)&&(first->data == second->data)&&
              equal(first->left_child,second->left_child) && equal(first->right_child,second->right_child)));
}
5.利用队列对二叉树进行层序遍历
void level_order(tree_pointer temp)
{
    int front=rear=0;
    tree_pointer queue[MAX_QUEUE_SIZE];
    if(!temp)
    {
       return;
    }
    addq(front,&rear,temp);
    for(;;)
    {
       temp = deleteq(&front,rear);
       if(temp)
       {
           printf("%d",temp->data);
           if(temp->left_child)
           {
               addq(front,&rear,temp->left_child);
           }
           if(temp->right_child)
           {
               addq(front,&rear,temp->right_child);
           }
       }
       else
       {
           break;
       }
    }
    
}
6.迭代的中序遍历
void iter_inorder(tree_pointer node)
{
    int top = -1;
    tree_pointer stack[MAX_STACK_SIZE];
    for(;;)
    {
        for(;node,node->left_child)
        add(&top,node);
        node = delete(&top);
        if(!node)break;
        printf("%d",node->data);
        node = node->right_child;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值