1. 程式人生 > >DS樹+圖綜合練習--二叉樹高度

DS樹+圖綜合練習--二叉樹高度

題目描述 給出一棵二叉樹,求它的高度。二叉樹的建立採用前面實驗的方法。

注意,二叉樹的層數是從1開始

輸入

第一行輸入一個整數t,表示有t個二叉樹

第二行起輸入每個二叉樹的先序遍歷結果,空樹用字元‘0’表示,連續輸入t行

輸出 每行輸出一個二叉樹的高度

樣例輸入
1
AB0C00D00
樣例輸出
3

思路

#include<iostream>
#include<string>
#include<queue> 
using namespace std;
  
class BiTreeNode{
    public:
        char data;
        BiTreeNode *LeftChild;
        BiTreeNode *RightChild;
        BiTreeNode():LeftChild(NULL), RightChild(NULL){
              
        }
        ~BiTreeNode(){
              
        }
};
  
class BiTree{
    private:
        BiTreeNode *Root;
        int pos;
        string strTree;
        BiTreeNode* CreateBiTree(){
            BiTreeNode *T;
            char ch;
            ch= strTree[pos++];
          
              
            if(ch== '0')
              T= NULL;
            else{
                T= new BiTreeNode();
                T->data= ch;
                T->LeftChild= CreateBiTree();
                T->RightChild= CreateBiTree();
            }
            return T;
        }
    
        void  getLeaf(BiTreeNode* t, int deep){//傳入父節點和父節點的高度
            if(t){
                deep++;
                 
                if(!t->LeftChild&&!t->RightChild){
                    //cout<<t->data<<' ';
                    if(maxx< deep)
                     maxx= deep;
                     
                }
                getLeaf(t->LeftChild, deep);
                getLeaf(t->RightChild, deep);
                 
            }
        }
         
    public:
        int leaf;
        queue<char> qu;
        int maxx;
         
        BiTree(){
              
        }
        ~BiTree(){
              
        }
        void CreateTree(string TreeArray){
            pos= 0;
            leaf= 0;
            maxx= 0;
            strTree.assign(TreeArray);
            Root= CreateBiTree();
        }
       
        void getLeaf(){
            getLeaf(Root, 0);
        }
     
};
  
int main(){
    int t;
    cin>>t;
      
    while(t--){
        string str;
        BiTree tree;
        cin>>str;
         
        tree.CreateTree(str);
        tree.getLeaf();
       
         
        cout<<tree.maxx<<endl;;
    }
    return 0;
}