zoukankan      html  css  js  c++  java
  • 递归建立二叉树

    转载:递归建立二叉树

    假设二叉树为:

                                            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 = c;
            createBiTree(T->leftChild);
            createBiTree(T->rightChild);
        }
    }
    
    int main()
    {
        BiTree T;
        createBiTree(T);
    
        return 0;
    }

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

  • 相关阅读:
    区间DP入门
    Prime Permutation(思维好题 )
    小字辈 (bfs好题)
    博弈论小结之尼姆博弈
    Hometask
    Lucky Sum (dfs打表)
    对称博弈
    尼姆博弈
    莫队算法 ( MO's algorithm )
    Codeforces 988D Points and Powers of Two ( 思维 || 二的幂特点 )
  • 原文地址:https://www.cnblogs.com/akrusher/p/5965214.html
Copyright © 2011-2022 走看看