码迷,mamicode.com
首页 > 其他好文 > 详细

基本二叉树的实现

时间:2016-01-23 21:40:41      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

废话不说,直接看代码:

BTree.h

#pragma once
#include <iostream>
using namespace std;

struct BTNode
{
    int data;
    BTNode *lchlid, *rchild;
};

class BTree
{
public:
    BTree();
    ~BTree();
public:
    void CreateBTree(BTNode *&root);
    void PreorderTraversal(BTNode *root);//先序遍历
    void InorderTraversal(BTNode *root); //中序遍历
    void PostorderTraversal(BTNode *root);//后序遍历
    int GetNodeCount(BTNode *root);       //获得结点个数
    int GetDepth(BTNode *root);              //获得二叉树的深度
    int GetLeafCount(BTNode *root);          //获得叶子结点个数     
};

 

BTree.cpp

#include "BTree.h"


BTree::BTree()
{
}


BTree::~BTree()
{
}

void BTree::CreateBTree(BTNode *&root)
{
    int value;
    cin >> value;
    if (value == -1)
        root = NULL;
    else
    {
        root = new BTNode;
        root->data = value;
        CreateBTree(root->lchlid);
        CreateBTree(root->rchild);
    }
}

void BTree::PreorderTraversal(BTNode *root)
{
    if (root)
    {
        cout << root->data <<  ;
        PreorderTraversal(root->lchlid);
        PreorderTraversal(root->rchild);
    }
}

void BTree::InorderTraversal(BTNode *root)
{
    if (root)
    {
        InorderTraversal(root->lchlid);
        cout << root->data <<  ;
        InorderTraversal(root->rchild);
    }
}

void BTree::PostorderTraversal(BTNode *root)
{
    if (root)
    {
        PostorderTraversal(root->lchlid);
        PostorderTraversal(root->rchild);
        cout << root->data <<  ;
    }
}

int BTree::GetNodeCount(BTNode *root)
{
    if (root == NULL) return 0;
    return GetNodeCount(root->lchlid) + GetNodeCount(root->rchild) + 1;
}

int BTree::GetDepth(BTNode *root)
{
    if (root == NULL)
        return -1;
    int dep1 = GetDepth(root->lchlid);
    int dep2 = GetDepth(root->rchild);
    if (dep1 > dep2)
        return dep1 + 1;
    else
        return dep2 + 1;
}

int BTree::GetLeafCount(BTNode *root)
{
    if (root == NULL) return 0;
    else if (root->lchlid == NULL && root->rchild == NULL)
        return 1;
    else
        return GetLeafCount(root->lchlid) + GetLeafCount(root->rchild);
}


int main()
{
    BTNode *root = NULL;
    BTree *tree = new BTree;
    tree->CreateBTree(root);
    cout << "\n先序遍历:\n";
    tree->PreorderTraversal(root);
    cout << "\n中序遍历:\n";
    tree->InorderTraversal(root);
    cout << "\n后序遍历:\n";
    tree->PostorderTraversal(root);
    cout << "\n结点个数:" << tree->GetNodeCount(root) << endl;
    cout << "\n二叉树深度:" << tree->GetDepth(root) << endl;
    cout << "\n叶子结点个数:" << tree->GetLeafCount(root) << endl;
    system("pause");
    return 0;
}

 

测试结果:输入1,2,3,4,5,6,-1,7,-1,8,9,-1,-1 ,-1,-1,-1,-1,-1,-1

    即如下图所示的二叉树

    技术分享

输出如下图:

技术分享

基本二叉树的实现

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5154026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!