当前位置:首页>科技>正文

求二叉树的求节点数量算法 统计二叉树的节点个数

2023-06-07 17:04:56 互联网 未知 科技

 求二叉树的求节点数量算法 统计二叉树的节点个数

求二叉树的求节点数量算法

int display(Item *root)
{
Item *p
p=root
if(p->leftChild==NULL&&p->rightChild==NULL){
return 1
}
if(p->leftChild!=NULL){
return (1 display(p->leftChild))
}
if(p->rightChild!=NULL){
return  (1 display(p->rightChild))
}
}
临时写的,可能会有点小问题,思想就是递归

统计二叉树的节点个数

#include#include typedef struct Bin_Tree_Node{ struct Bin_Tree_Node *left_child struct Bin_Tree_Node *right_child int data }Bin_Tree_Node //将输入的序列按照二叉树的先序遍历创建二叉树 void CreateBinTree( Bin_Tree_Node **p_root ){ static int input_data scanf("%d", &input_data ) if( input_data == -1 ) { (*p_root) = NULL return } else { (*p_root) = (Bin_Tree_Node *)malloc( sizeof(Bin_Tree_Node) ) (*p_root)->data = input_data CreateBinTree( &(*p_root)->left_child ) CreateBinTree( &(*p_root)->right_child ) }} //求二叉树中节点的个数int BinTreeNodeCount( Bin_Tree_Node *root ){ int num, num1, num2 if( root==NULL ) { return 0 } else { num1 = BinTreeNodeCount( root->left_child ) num2 = BinTreeNodeCount( root->right_child ) num = num1 num2 1 return num }} int main(){ Bin_Tree_Node *root int node_num CreateBinTree( &root ) node_num = BinTreeNodeCount( root ) printf(" number of node: %d ", node_num ) system("pause") return 0}