树与二叉树的转化

来源:互联网 发布:a卡吃鸡优化 编辑:程序博客网 时间:2024/05/22 15:42

树的先序遍历对应二叉树的先序遍历;
树的后序遍历对应二叉树的中序遍历。

树转换为二叉树

(1)加线。在所有兄弟结点之间加一条连线。

(2)去线。树中的每个结点,只保留它与第一个孩子结点的连线,删除它与其它孩子结点之间的连线。

(3)层次调整。以树的根节点为轴心,将整棵树顺时针旋转一定角度,使之结构层次分明。(注意第一个孩子是结点的左孩子,兄弟转换过来的孩子是结点的右孩子)


struct bnode                   // 结点类型

{ struct bnode * lchild ;      // 左孩子指针

    ElemType data ;              // 抽象数据元素类型

    struct bnode * rchild ;      // 右孩子指针

  }*root ;

 

生成二叉链表 C 算法1

#define LENG sizeof(struct bnode) /* 结点所占空间的大小*/

creat_tree(struct bnode ** root)    / *root  指向指针 的指针*/

{ char ch ;

  scanf("%c",&ch) ;                   /* 输入结点, 字符型*/

  if (ch == ‘ F ’) (* root)=NULL ;        /* 生成空二叉树*/

  else                                /* 生成非空二叉树*/

      { (* root)=(struct bnode *)malloc(LENG) ;

       (* root)->data=ch ;                  /* 生成根结点 */

       creat_tree(& (* root)->lchild) ;    /* 递归生成左子树*/

     creat_tree(& (* root)->rchild) ;    /* 递归生成右子树*/

      }     

  return ;

  }

 

  main( )  /* 主函数*/

 

{ struct bnode *root ;

    creat_tree(& root) ;

  }

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

 

建立二叉链表算法2, 避免使用 指针的指针

#define LENG sizeof(struct bnode) // 结点所占空间的大小

struct bnode *CreatBiTree( )

{ char ch ;

  struct bnode *root ;        /* 二叉链表根结点指针*/

  scanf("%c",&ch) ;           /* 输入结点, 字符型*/

  if (ch==' ')root=NULL ;     /* 生成空二叉树*/

  else

  { root=(struct bnode *)malloc(LENG ) ;/* 生成根结点*/

    root->data=ch ;

    root->lchild=CreatBiTree( ) ; /* 递归构造左子树 */

    root->rchild=CreatBiTree( ) ; /* 递归构造右子树 */

   }

  return root ;

  }

  main( )  /* 主函数*/

  { struct bnode *root ;

   root=CreatBiTree( ) ;

  }

 

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

 

前序遍历递归算法

preorder(struct bnode *root)  

   //root 为根指针

{   if (root)         // 为非空二叉树

      { printf("%c,",root->data) ;  // 访问根结点

      preorder(root->lchild) ;    // 递归遍历左子树

      preorder(root->rchild) ;    // 递归遍历右子树

    }

  }

 

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

 

inorder(struct bnode *root)

  //root 为根指针

{ if (root)     // 为非空二叉树  

    { inorder(root->lchild) ;     // 递归遍历左子树

    printf("%c",root->data)    // 访问根结点

    inorder(root->rchild) ;     // 递归遍历右子树

   }

  }

 

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

中序遍历 非递归算法

inorder2(struct bnode *t)        //t 为根指针

{ struct bnode *st[maxleng+1] ;  // 定义指针( 地址) 栈st

  int top=0 ;                  // 置空栈

  do           

  { while(t)                      // 为非空二叉树

    { if (top==maxleng) exit("overflow") ;// 栈已满, 退出

      st[++top]=t ;              // 根地址进栈

      t=t->lchild ;              //t 移向左子树

     }                      

    if (top)                      // 为非空栈  

    { t=st[top--] ;              // 弹出根地址

      printf("%c",t->data)       // 访问根结点

      t=t->rchild ;              // 遍历右子树

     }

   }

   while(top||t) 



原创粉丝点击