關於二叉樹的一些操作

來源:互聯網
上載者:User

二叉樹的結構定義為:

struct BinTree{int data;BinTree* lchild;BinTree* rchild;};

樹深度的遞迴演算法:

//求樹深度的遞迴演算法,根深度為1int Depth(BinTree T){int m,n;if(!T)return 0;else{m=Depth(T->lchild);n=Depth(T->rchild);return (m>n?m:n)+1;}}

二叉樹中以值為x的結點為根的子樹深度:

//求二叉樹中以值為x的結點為根的子樹深度int Get_Sub_Depth(BinTree T, int x){int m,n;if(T){if(T->data==x)return Depth(T);//找到了值為x的結點,求x為根的子樹的其深度else{//在左右子樹中繼續尋找if(T->lchild)m=Get_Sub_Depth(T->lchild,x);if(T->rchild)n=Get_Sub_Depth(T->rchild,x);}return m>n?m:n;}return 0;}

 

交換所有結點的左右子樹:

//交換所有結點的左右子樹void Bitree_Revolute(BinTree* T){if(T){//交換左右子樹BinTree* temp;temp = (BinTree*)malloc(sizeof(BinTree));temp = T->lchild;T->lchild = T->rchild;T->rchild = temp;if(T->lchild)Bitree_Revolute(T->lchild);if(T->rchild)Bitree_Revolute(T->rchild); }}

根據順序儲存結構建立二叉鏈表:

//根據順序儲存結構建立二叉鏈表int CreateBitree_SqList(BinTree &T,SqList sa){BinTree ptr[sa.last+1]; //該數組儲存與sa中各結點對應的樹指標if(!sa.last){T=NULL; //空樹Return 1;}ptr[1]=(BTNode*)malloc(sizeof(BTNode));ptr[1]->data=sa.elem[1]; //建立樹根T=ptr[1]; T->lchild=T->rchild=NULL;for(i=2;i<=sa.last;i++){if(!sa.elem[i])return 0; //順序錯誤ptr[i]=(BTNode*)malloc(sizeof(BTNode));ptr[i]->data=sa.elem[i];ptr[i]->lchild=ptr[i]->rchild=NULL;j=i/2; //找到結點i的雙親jif(i==j*2) ptr[j]->lchild=ptr[i]; //i是j的左孩子else if(i==2*j+1)ptr[j]->rchild=ptr[i]; //i是j的右孩子}return 1;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.