zoukankan      html  css  js  c++  java
  • C++求二叉树的最大高度差

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    template<typename Type>
    struct Node
    {
        Type data;
        Node *left;
        Node  *right;
        Node(Type d = Type()):data(d),left(NULL),right(NULL){}
        //vs2013太变态了,一个空格出现未知文件尾出错,我找了10分钟。
    };
    
    template<typename Type>
    class Tree
    {
    public:
        Tree()
        {
            root = NULL;
            flags = '#';
        }
        void Insert(const char *str)
        {
            Insert(root, str);
        }
        void Printf()
        {
            Printf(root);
        }
        int GetLength()//求最大高度差。
        {
            int i = GetLengthMax();
            int j  = GetLengthMin();
            return i - j;
        }
        int GetLengthMax()
        {
            return GetLengthMax(root);
        }
        int GetLengthMin()
        {
            return GetLengthMin(root);
        }
    private:
        int GetLengthMax(Node<Type> *t)
        {
            if (t == NULL)
                return 0;
            else
            {
                return GetLengthMax(t->left)>GetLengthMax(t->right)?GetLengthMax(t->left)+1:GetLengthMax(t->right) + 1;
            }
        }
        int GetLengthMin(Node<Type>* t)
        {
            if (t == NULL)
                return 0;
            else
            {
                return GetLengthMin(t->left)<GetLengthMin(t->right) ? GetLengthMin(t->left) + 1 : GetLengthMin(t->right) + 1;
            }
        }
        void Printf(Node<Type> *t)
        {
            if (t != NULL)
            {
                cout << t->data << "  ";
                Printf(t->left);
                Printf(t->right);
            }
        }
        void Insert(Node<Type> *&t, const char*& s)
        {
            if (*s == flags)
            {
                t = NULL;
                return;
            }
            else
            {
                t = new Node<Type>(*s);
                Insert(t->left,++s);
                Insert(t->right,++s);
            }
        }
    private:
        Node<Type> *root;
        char flags;
    };
    
    int main()
    {
        Tree<char> t;
        char *s = new char[20];//1234####56##7
        strcpy(s,"1##");
        t.Insert(s);
        t.Printf();
        cout << endl;
        cout << t.GetLength()<< endl;
        return 0;
    }
  • 相关阅读:
    etcd 部署、备份与恢复
    centos7 mysql 5.7.24 源码编译
    生产中两块网卡bond
    shell 免密批量执行脚本
    MegaCli 清除与添加raid5
    centos7 mongodb4.0.2 复制集主从部署
    centos6.6 部署 cacti 并采集交换机流量
    shell 批量远程主机执行命令
    拯救系统文件只读模式
    下推自动机(PDA)在程序设计中的应用
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5220918.html
Copyright © 2011-2022 走看看