二叉链表存储结构,交换分支点左右子树算法(C)

今晚感觉不错,56个题,错了6个,一看是关于二叉树链表的有2个,所以需要重视这部分。

二叉链表存储结构,交换分支点左右子树算法:

f(Node*   root,Node*   child)  
  {  
          if   (root==child)   {output   the   stack;return;}  
          if   (root->left)   {  
                        stack.push(root->left);  
                        f(root->left,child);  
                        stack.pop();  
          }  
          if   (root->right)   {  
                        stack.push(root->right);  
                        f(root->right,child);  
                        stack.pop();  
          }  
  }  
   
  void   main()  
  {  
          stack.push(root);  
          f(root,child);  
  }  
  程序没检测,就是这个大概意思,路径要用堆栈来保存!!

-----------------------------------------------------------------------------

(1)编写建立二叉树的算法。
(2)验证二叉树的先序、中序、后序遍历算法
(3)编写二叉树的左右子树交换算法
上面这些都比较简单,程序如下:

#include <stdio.h>
#include <malloc.h>

typedef struct tree
{
char  data;
struct tree *l;/*左儿子*/
struct tree *r;/*右儿子*/
}tr;

/*先序建立二叉树*/
tr *create(tr *t)
{      
tr *k=NULL;
char ch;

scanf("%s",&ch);
if(ch=='#')
{
  t=NULL;
}
else
{
  t=(tr *)malloc(sizeof(tr));
  t->data=ch;
  t->l=create(k);
  t->r=create(k);
}
return t;
}

/*先序遍历*/
void preOrder(tr *t)
{
if(t)
{
  printf("%c/t",t->data);
  preOrder(t->l);
  preOrder(t->r);
}
}

/*中序遍历*/
void inOrder(tr *t)
{
if(t)
{
  inOrder(t->l);
  printf("%c/t",t->data);
  inOrder(t->r);
}
}

/*后序遍历*/
void postOrder(tr *t)
{
if(t)
{
  postOrder(t->l);
  postOrder(t->r);
  printf("%c/t",t->data);
}
}

/*左右子树交换*/
void switchChild(tr *t)
{
if(t)
{
  tr *temp;
 
  temp=t->l;
  t->l=t->r;
  t->r=temp;
  switchChild(t->l);
  switchChild(t->r);
}
}

main()
{
tr *head=NULL;

head=create(head);
printf("/n The preOrder is:");
preOrder(head);
printf("/n The inOrder is:");
inOrder(head);
printf("/n The postOrder is:");
postOrder(head);
printf("/n");
switchChild(head);
}


------------------------------------------------------------------------

关于二叉链表概念:http://www.doc88.com/p-08368579078.html

---------------------------------------------------------------------------

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值