zoukankan      html  css  js  c++  java
  • 二叉树的建立与遍历(山东理工OJ)

    题目描写叙述
    已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(当中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
    输入
    输入一个长度小于50个字符的字符串。
    输出
    输出共同拥有4行:
    第1行输出中序遍历序列;
    第2行输出后序遍历序列。
    第3行输出叶子节点个数;
    第4行输出二叉树深度。
    演示样例输入
    abc,,de,g,,f,,,
    演示样例输出
    cbegdfa
    cgefdba
    3
    5
    #include <iostream>
    using namespace std;
    typedef char Elem_Type;
    typedef struct BiTNode
    {
        Elem_Type data;
        BiTNode *lchild;
        BiTNode *rchild;
    }BiTNode;
    void CreateBiTree(BiTNode **root)
    {
        Elem_Type temp;
        cin>>temp;
        if(temp == ',')
         *root = NULL;
        else
        {
            *root = new BiTNode;
            (*root)->data = temp;
            CreateBiTree( &(*root)->lchild );
            CreateBiTree( &(*root)->rchild );
        }
    }
    void InOrderTraverse(BiTNode *root)//中
    {
        if( root )
        {
            InOrderTraverse( root->lchild);
            cout<<root->data;
            InOrderTraverse( root->rchild);
        }
    }
    void PostOrderTraverse(BiTNode *root)
    {
        if( root )
        {
            PostOrderTraverse( root->lchild);
            PostOrderTraverse( root->rchild);
            cout<<root->data;
        }
    }
    int LeafNodes( BiTNode *root)
    {
        static int count =0;
        if( !root )
          return 0;
        if( !root->lchild && !root->rchild)
          count++;
        LeafNodes(root->lchild);
        LeafNodes(root->rchild);
        return count;
    }
    int BiTreeDepth(BiTNode *root)
    {
        if( !root )
          return 0;
        return (BiTreeDepth(root->lchild) > BiTreeDepth(root->rchild)?
                BiTreeDepth(root->lchild) : BiTreeDepth(root->rchild)) + 1;
    }
    int main(void)
    {
        BiTNode *root = NULL;
        CreateBiTree(&root);
        InOrderTraverse(root);
        cout<<endl;
        PostOrderTraverse(root);
        cout<<endl;
        cout<<LeafNodes( root)<<endl;
        cout<<BiTreeDepth(root)<<endl;
        return  0;
    }
    /**************************************
    	Problem id	: SDUT OJ 2136 
    	User name	: 李俊 
    	Result		: Accepted 
    	Take Memory	: 456K 
    	Take Time	: 10MS 
    	Submit Time	: 2014-05-05 23:13:18  
    **************************************/
  • 相关阅读:
    Linux私房菜——防火墙部分笔记
    ubuntu
    序列求和
    圆的面积
    Fibonacci数列
    JavaScript中定义数组
    C语言中的EOF
    jQuery获取的值去掉px
    jQuery中单引号和双引号的使用
    jQuery报错:Uncaught ReferenceError: $ is not defined
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5061024.html
Copyright © 2011-2022 走看看