1. 程式人生 > 其它 >基於二叉樹的演算法

基於二叉樹的演算法

1.統計二叉樹中度為1的節點個數

int NodeCount(BiTree bt){
    if(bt == null) return 0;
    if(bt->lchild == null && bt->rchild != null || bt->lchild != null && bt->rchild == null)
        return 1+NodeCount(bt->lchild) + NodeCount(bt->rchild);
    return NodeCount(bt->lchild) + NodeCount(bt->rchild);
}

2.統計二叉樹中度為2的節點個數

int NodeCount(BiTree bt){
    if(bt == null) return 0;
    if(bt->lchild != null && bt->rchild != null)
        return 1+NodeCount(bt->lchild) + NodeCount(bt->rchild);
}

3.統計二叉樹中度為0的節點個數(葉節點)

int NodeCount(BiTree bt){
    if(bt == null) return 0;
    if(bt->lchild == null && bt->rchild == null)
        return 1;
    else
        return NodeCount(bt->lchild) + NodeCount(bt->rchild);
}

4.計算二叉樹高度

int height(BiTree bt){
    if(bt == null) return 0;
    int LHeight = height(bt->left);
    int RHeight = height(bt->right);
    return (LHeight > RHeight ? LHeight : RHeight) + 1;
}

5.計算二叉樹最大高度(基於先序遍歷)

int count[MaxSize];
int max = -1;
void width(BiTree bt, int k){
    if(bt == null) return;
    count[k]++;    //該層節點數+1
    if(max<count[k]) max = count[k];
    width(bt->lchikd, k+1);
    width(bt->rchild, k+1);
}

6.刪除二叉樹中所有葉節點

void Del_0(BiTree bt){
    BiTree *p = bt;
    if((p->lchild == null && p->rchild == null) || p == null)
        free(p);
        return;
    if(p->lchild->lchild == null && p->lchild->rchild == null)
        free(p->lchild);    //說明是葉節點,刪掉
        p->lchild = null;
    else(p->rchild->lchild == null && p->rchild->rchild == null)
        free(p->rchild);
        p-rchild = null;
    Del_0(p->lchild);
    Del_0(p->rchild);
}

7.計算二叉樹指定節點所在層次

int level(BiTree bt, BiTree *p){
    int d1,d2;
    if(bt == null) return 0;
    if(bt == p) return 1;
    d1 = level(bt->lchild, p);
    d2 = level(bt->rchild, p);
    if(d1 || d2) return 1+(d1>d2 ? d1:d2);
    retrun 0;
}

8.交換二叉樹左右子樹

void swap(BiTree bt){
    if(bt){
        swap(bt->lchild);
        swap(bt->rchild);
        BiTree *temp = bt->lchild;
        bt->lchild = bt->rchild;
        bt->rchild = temp;
    }
}

9.後序遍歷非遞迴演算法

void PostOrder(BiTree T){
    InitStack(S);
    BiTree *p = T;
    BiTree *r = null;
    while(p || !IsEmpty(S)){
        if(p){
            Push(S,p);
            p = p->lchild;
        }else{
            GetTop(S,p);
            if(p->rchild && p->rchild != r){    //判斷是否有右子樹
                p = p->rchild;
            }else{
                Pop(S,p);
                visit(p->data);
                r = p;
                p = null;
            }
        }
    }
}
作者:不像話 出處:https://www.cnblogs.com/jake-jin/ github地址:https://github.com/buxianghua 若標題中有“轉載”字樣,則本文版權歸原作者所有。歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利.