求二叉樹的高度,寬度 節點個數 葉子節點個數

2021-07-25 10:39:38 字數 2265 閱讀 3898

#include

#include

#include

/*實現求二叉樹的高度,寬度、節點個數、葉子節點個數*/

typedef struct node

tnode,*ptnode;

ptnode createtree()

else

ptnode->

data

=data;

ptnode->lchild = createtree();

ptnode->rchild = createtree();

}return ptnode;

}void preordertree(ptnode root)

}//求二叉樹葉子節點個數----遞迴求解

int leaf(ptnode root)

else

if(root->lchild==

null

&& root->rchild==

null)

else

} //求二叉樹節點個數

int nodenum(ptnode root)

return nodenum(root->lchild)+nodenum(root->rchild)+

1;}

//二叉樹深度

int deep(ptnode root)

//二叉樹寬度

typedef struct qnode

qnode,*pqnode;

typedef struct queue

queue,*pqueue;

pqueue initqueue()

pqueue->front = pqueue->rear = pqnode;

pqueue->rear->next =

null;

return pqueue;

}bool empty(pqueue pqueue)

void enqueue(pqueue pqueue,ptnode ptnode)

pqnode pqnode = (pqnode)malloc(sizeof(qnode));

if(pqnode==

null)

pqnode->ptnode = ptnode;

pqnode->next =

null;

pqueue->rear->next = pqnode;

pqueue->rear = pqnode;

}ptnode getqueue(pqueue pqueue)

return pqueue->front->next->ptnode;

}void dequeue(pqueue pqueue)

pqnode pqnode=pqueue->front->next;

pqueue->front->next = pqnode->next;

printf("%d出隊\n",pqnode->ptnode->

data);

if(pqnode==pqueue->rear)

free(pqnode);

}int size(pqueue pqueue)

int size=

0; pqnode p = pqueue->front->next;

while(p!=

null)

return size;

}int width(ptnode root)

int lastwidth =

0; //上一層寬度

int templastwidth =

0; int curwidth =

0;//當前層寬度

int width =

1; //二叉樹寬度

pqueue pqueue = initqueue();

enqueue(pqueue,root);

lastwidth =

1; ptnode p =

null;

while(!empty(pqueue))

if(p->rchild!=

null)

templastwidth--;

}curwidth = size(pqueue);

width = curwidth>width?curwidth:width;

lastwidth = curwidth;

}return width;

}void main()

二叉樹 高度,寬度和節點個數

對於二叉樹的演算法問題,我們可以根據二叉樹本身的定義的遞迴性質求解,或者使用對二叉樹的遍歷演算法進行求解.下面我們看幾個關於二叉樹高度,寬度和節點個數的演算法 一,求二叉樹的高度 1,使用二叉樹遞迴定義的性質求二叉樹的高度 如果根節點為空,返回0 否則 遞迴求左子樹高度 getheightrecur...

二叉樹的節點個數 葉子節點個數 第k層的節點個數

class binarytreenode public class nodesstatistics 求二叉樹中葉子節點的個數 1 如果二叉樹為空,返回0 2 如果二叉樹不為空,返回1 3 如果二叉樹不為空,且左右子樹不同時為空,返回左子樹中葉子節點個數加上右子樹中葉子節點個數。param root ...

求完全二叉樹的節點個數

題目 給定乙個完全二叉樹的頭結點,求節點的個數。要求時間複雜度低於o n 思路 利用完全二叉樹的特點,分別求出左右子樹的高度l1,r1,如果l1 r1,則左子樹是滿二叉樹,根據高度直接求出節點 個數,接著遞迴右子樹。同理如果l1 r1,則右子樹是滿二叉樹,直接得到右子樹的節點個數,遞迴左子樹。pub...