二叉树建立,遍历

二叉树
样例输入 :

1 2 4 0 7 0 0 0 3 5 8 0 0 9 0 0 6 0 0

空的用零代替,补充为完全二叉树。
因为是输入数字 ,所以注意输入之间有空格。

样例输出:

二叉树建立成功
二叉树总节点数为:9
二叉树深度为:4
二叉树叶子节点数为:4
前序遍历结果:
1 2 4 7 3 5 8 9 6
中序遍历结果:
4 7 2 1 8 5 9 3 6
后序遍历结果:
7 4 2 8 9 5 6 3 1

代码 :

#include <iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

typedef int TelemType;

typedef struct BinaryTreeNode
{
    TelemType data;
    struct BinaryTreeNode *Left;
    struct BinaryTreeNode *Right;
}Node;


//创建二叉树,顺序依次为中间节点->左子树->右子树
Node* createBinaryTree()
{
    Node *p;
    TelemType ch;
    cin>>ch;
    if(ch == 0)     //如果到了叶子节点,接下来的左、右子树分别赋值为0
    {
        p = NULL;
    }
    else
    {
        p = (Node*)malloc(sizeof(Node));
        p->data = ch;
        p->Left  = createBinaryTree();  //递归创建左子树
        p->Right = createBinaryTree();  //递归创建右子树
    }
    return p;
}

//先序遍历
void preOrderTraverse(Node* root)
{
    if( root )
    {
        cout<<root->data<<' ';
        preOrderTraverse(root->Left);
        preOrderTraverse(root->Right);
    }
}

//中序遍历
void inOrderTraverse(Node* root)
{
    if( root )
    {
        inOrderTraverse(root->Left);
        cout<<root->data<<' ';
        inOrderTraverse(root->Right);
    }
}

//后序遍历
void lastOrderTraverse(Node* root)
{
    if( root )
    {
        lastOrderTraverse(root->Left);
        lastOrderTraverse(root->Right);
        cout<<root->data<<' ';
    }
}

//二叉树节点总数目
int Nodenum(Node* root)
{
    if(root == NULL)
    {
        return 0;
    }
    else
    {
        return 1+Nodenum(root->Left)+Nodenum(root->Right);

    }
}

//二叉树的深度
int DepthOfTree(Node* root)
{
    if(root)
    {
        return DepthOfTree(root->Left)>DepthOfTree(root->Right)?DepthOfTree(root->Left)+1:DepthOfTree(root->Right)+1;
    }
    if( root == NULL )
    {
        return 0;
    }
}

//二叉树叶子节点数
int Leafnum(Node* root)
{
    if(!root)
    {
        return 0;
    }
    else if(  (root->Left == NULL) && (root->Right == NULL) )
    {
        return 1;
    }
    else
    {
        return  (Leafnum(root->Left) + Leafnum(root->Right)) ;
    }
}


int main()
{
    Node *root = NULL;
    root = createBinaryTree();
    printf("二叉树建立成功");
    cout<<endl;

    cout<<"二叉树总节点数为:"<<Nodenum(root)<<endl;

    cout<<"二叉树深度为:"<<DepthOfTree(root)<<endl;

    cout<<"二叉树叶子节点数为:"<<Leafnum(root)<<endl;

    cout<<"前序遍历结果:"<<endl;
    preOrderTraverse(root);
    cout<<endl;

    cout<<"中序遍历结果:"<<endl;
    inOrderTraverse(root);
    cout<<endl;

    cout<<"后序遍历结果:"<<endl;
    lastOrderTraverse(root);
    cout<<endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值