データ構造とアルゴリズム(バイナリツリーの各ノードの高さを前の順序で出力)

バイナリツリーのデータ要素が文字であると仮定すると、バイナリチェーンストレージ構造が採用されています。バイナリツリーADT実装のコードのほとんどが提供されています。これは、完全なプレオーダーシーケンスを使用してバイナリツリーを作成します。以下の2つの操作機能を追加してください。注:回答領域には2つの関数のみが記述されており、他のコードは変更、再書き込み、または送信できません。
(1)特定のノードをルートバイナリツリーの高さを計算し、
(2)出力プレオーダー配列中の各要素ノードをルートとするサブツリーの高さ;
例えば:右図のように二分木
ここに画像の説明を挿入
入力:

ABD@@E@@C@F@@

出力:

Height(A)=3
Height(B)=2
Height(D)=1
Height(E)=1
Height(C)=2
Height(F)=1

:指定されたコードは次の通りである
の#include <iostreamの>
する#include <STDLIB.H>
;名前空間STDを使用して、
//データ要素タイプ
のtypedefチャーElemType;
//バイナリツリーノードの定義
のtypedef構造体のTreeNode
{ElemTypeデータ、
構造体のTreeNode * LSON、 * rson;
} TreeNode;
//バイナリツリー
クラスBinaryTree
{private:
TreeNode * root;
public:
BinaryTree(){root = NULL;};
〜BinaryTree(){MakeEmpty(root);}
void MakeEmpty(TreeNode * t);
void create(){root = cp_create(root);}; //完全なプレオーダーでバイナリツリーを作成し、@を使用してnullポインターを表す
TreeNode * cp_create(TreeNode * t);
// ******関数の高さ* *******
int height(TreeNode * t); //二分木の高さを見つける
void output(){Pro_height(root);};
// ******追加する関数Pro_height **********
void Pro_height(TreeNode * t); //それぞれ前の順序で出力要素ノードがルートであるサブツリーの高さ
};
//バイナリツリーを空にする
BinaryTree :: MakeEmpty(TreeNode * t)
{if(t!= NULL)
{MakeEmpty(t-> lson);
MakeEmpty(t-> rson );
delete t;
}
}
//完全なプレオーダーシーケンスはバイナリツリーを作成し、nullポインターは@
TreeNode * BinaryTree :: cp_create(TreeNode * t)
{ElemType v;
cin >> v;
if(v!= '@')で表されます
{t = new TreeNode;
t-> data = v;
t-> lson = cp_create(t-> lson);
t-> rson = cp_create(t-> rson);
}
else t = NULL;
return t;
}
// ******************** 2つの関数を追加する必要があります********************** ********

// ************************************************ *******************************
//主函数
int main()
{BinaryTree t;
t.create();
t.output();
0を返します。
}

int BinaryTree::height(TreeNode*t)
{
    
    
    if(t==NULL)return 0;
    else
    {
    
    
        if(height(t->lson)>height(t->rson))return 1+height(t->lson);
        else return 1+height(t->rson);
    }
}
void BinaryTree::Pro_height(TreeNode*t)//前序
{
    
    
    if(t!=NULL)
    {
    
    
        cout<<"Height("<<t->data<<")="<<height(t)<<endl;
        Pro_height(t->lson);
        Pro_height(t->rson);
    }
}

おすすめ

転載: blog.csdn.net/upc122/article/details/106668862