首页 > 代码库 > 递归建立二叉树

递归建立二叉树

转载:递归建立二叉树

假设二叉树为:

                                        a

                              b                 c

                                   d                 e

       

         因为程序中要知道叶子结点(终点),所以要将上面的二叉树变成扩展二叉树 (把叶子结点的孩子补成#, 用作标记),  扩展后就变成了:         

                                       a

                            b                    c

                       #        d          #       e

                              #    #             #    #

 

          那么,在输入的时候,需要输入: ab#d##C#e##      (注意,输入后,按enter键即可)   ,程序如下:

#include<iostream>using namespace std;typedef struct node{    struct node *leftChild;    struct node *rightChild;    char data;}BiTreeNode, *BiTree;void createBiTree(BiTree &T){    char c;    cin >> c;    if(# == c)        T = NULL;    else    {        T = new BiTreeNode;        T->data =http://www.mamicode.com/ c;        createBiTree(T->leftChild);        createBiTree(T->rightChild);    }}int main(){    BiTree T;    createBiTree(T);    return 0;}

经遍历验证可知,上面的程序是正确的, 至于如何遍历,以后的博文会陆续给出相应的程序

递归建立二叉树