標籤:== 建構函式 父節點 public 檔案 bsp cout ack fine
測試是否有左孩子 hasLChild(x)、右孩子函數 hasRChild(x),以及是否右孩子函數 hasChild(x) 。
節點標頭檔:
#ifndef BINNODE_H#define BINNODE_H#include <iostream>//***************************************************************************************///代碼5.2 , BinNode狀態與性質的判斷///一、 判斷該節點是什麼!/// 是否是根節點、是否是左子節點、是否是右子節點、是否是分葉節點#define isRoot(x) (!((x).parent))#define isLChild(x) (!isRoot(x)&&(&(x)==(x).parent->lc)) //不是根節點,同時必須是父節點的左孩子#define isRChild(x) (!isRoot(x)&&(&(x)==(x).parent->rc)) //不是根節點,同時必須是父節點的右孩子///二、判斷該節點有什麼//判斷是否有孩子#define hasLChild(x) ((x).lc!=NULL) //判斷節點x是否有左孩子#define hasRChild(x) ( (x).rc ) //判斷節點x 是否有右孩子#define hasChild(x) ( hasLChild(x)||hasRChild(x)) //判斷節點x是否有孩子(左、右至少有一個)//判斷是否為分葉節點#define isLeaf(x) ( !hasChild(x) ) //判斷節點x是否是葉子節點//****************************************************************************************#define BinNodePosi(T) BinNode<T>* //節點位置typedef enum{RB_RED,RB_BLACK} RBColor;//節點顏色template <typename T>class BinNode{public: T data;//數值 int height; int npl;//Null Path Length(左式堆,也可直接用height代替) RBColor color; BinNodePosi(T) parent;//父節點 BinNodePosi(T) lc;//左子節點 BinNodePosi(T) rc;//右子節點 //建構函式 BinNode():parent(NULL),lc(NULL),rc(NULL),height(0),npl(1),color(RB_RED){} BinNode(T e,BinNodePosi(T) p=NULL,BinNodePosi(T) lc=NULL,BinNodePosi(T) rc=NULL, int h=0,int l=1,RBColor c=RB_RED) { data=e; parent=p; this->lc=lc,this->rc=rc;//此處添加this指標,以便將成員變數lc、rc與形參lc和rc區分 height=h; npl=l; color=c; }};#endif // BINNODE_H
下面是測試執行個體代碼:
#include <iostream>#include <binnode.h>#include <string>using namespace std;//1、測試根節點函數isRootvoid testRoot(BinNode<string> &node){ if(isRoot(node)) cout<<node.data<<" is root!"<<endl; else cout<<node.data<<" is not a root!"<<endl;}//2、測試左孩子函數isLChildvoid testLChild(BinNode<string> &node){ if(isLChild(node)) cout<<node.data<<" is left child!"<<endl; else cout<<node.data<<" is not left child!"<<endl;}//3、測試右孩子函數isRChildvoid testRChild(BinNode<string> &node){ if(isRChild(node)) cout<<node.data<<" is "<<node.parent->data<< "‘s right child!"<<endl; else cout<<node.data<<" is not right child!"<<endl;}//4、測試是否有左孩子函數void testHasLChild(BinNode<string> &node){ if(hasLChild(node)) cout<<node.data<<" has a left child: "<<endl; else cout<<node.data<<" has not left child!"<<endl;}//5、測試是否是分葉節點函數isLeaf()void testLeaf(BinNode<string> &node){ if(isLeaf(node)) cout<<node.data<<" is "<<node.parent->data<< "‘s leaf!"<<endl; else cout<<node.data<<" is not leaf"<<endl;}int main(){ BinNode<string> n1("node1"); BinNode<string> n0("node0"); BinNode<string> n2("node2"); BinNode<string> n3("node3"); //2、將n2設定為n1的左節點,測試isLChild()函數 n1.lc=&n2; n2.parent=&n1; testLChild(n2); //3、將n3設定為n1的右節點,測試isRChild()函數 n1.rc=&n3; n3.parent=&n1;//建立n1、n3之間的父子關係 testRChild(n3); //4、測試n3是否有左孩子 testHasLChild(n2); //5、測試分葉節點函數isLeaf testLeaf(n3); return 0;}
下面是測試結果:
二叉樹執行個體學習(二)