求二叉树的高度/销毁一颗二叉树【递归思想】

本文详细探讨了如何通过递归算法来计算二叉树的高度,并介绍了如何有效地销毁一棵二叉树。递归方法在解决这类问题中展现出其简洁性和效率。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<cassert>
using namespace std;
template<class T>
struct TreeNode
{
    T data;
    TreeNode<T>* left;
    TreeNode<T>* right;
    TreeNode(const T& x)
        :data(x)
        ,left(NULL)
        ,right(NULL)
    {}
};

template<class T>
class BinaryTree
{
    typedef TreeNode<T> Node;
public:
    BinaryTree(const T* arr,int sz,const T& invalib)//1.构造函数---前序构造二叉树
    {
        assert(arr);
        int index=0;
        _root=CreatTree(arr,sz,invalib,index);
    }
    ~BinaryTree()//2.析构函数
    {
        Destroy(_root);//销毁一颗二叉树
        _root=NULL;
    }

    int GetBinaryTreeHength()//3.求二叉树的高度
    {
        return _GetBinaryTreeDepth(_root);
    }
protected:
    Node* CreatTree(const T* arr,int sz,const T& invalib,int& index)//前序构造二叉树
    {
        assert(arr);
        Node* root=NULL;
        while (index<sz&&arr[index]!=invalib)
        {
            root=new Node(arr[index]);
            root->left=CreatTree(arr,sz,invalib,++index);//此处index必须前置++
            root->right=CreatTree(arr,sz,invalib,++index);//此处index必须前置++
        }
        return root;
    }



----------

    void Destroy(Node* root)//销毁一颗二叉树
    {
        //1.树为空,直接返回,无结点销毁
        if (root==NULL)
        {
            return ;
        }
        //2.树只有一个结点,则销毁该节点
        if (root->left==NULL&&root->right==NULL)
        {
            delete root;
            root=NULL;
            return;
        }
        //3.树的结点大于一个,则先销毁左子树,后销毁右子树
        Destroy(root->left);
        Destroy(root->right);
        delete root;
        root=NULL;
    }


----------


    int _GetBinaryTreeDepth(Node* root)//求二叉树的高度
    {
        //1.树为空,深度为0
        if (root==NULL)
        {
            return 0;
        }
        //2.树只有一个结点,深度为1
        if (root->left==NULL&&root->right==NULL)
        {
            return 1;
        }
        //3.树的结点超过一个:深度=左子树的深度和右子树深度中较大数的值+1;(1为树的根结点)
        int LeftDepth=_GetBinaryTreeDepth(root->left);
        int RightDepth=_GetBinaryTreeDepth(root->right);

        return LeftDepth>RightDepth?  LeftDepth+1:RightDepth+1;
    }
protected:
    Node* _root;
};

int main()
{
    int arr[]={1,2,3,'#','#',4,'#','#',5,6,'#','#','#'};
    int sz=sizeof(arr)/sizeof(arr[0]);
    BinaryTree<int>  bt(arr,sz,'#');
    cout<<"二叉树的高度"<<bt.GetBinaryTreeHength()<<endl;//3
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值