zoukankan      html  css  js  c++  java
  • 获取二叉树叶子节点个数

    //获取二叉树叶子节点个数
    
    #include<stdio.h>
    #include<stdlib.h>
    
    //用二叉链表存储方式建树(完全二叉树)
    typedef struct BitTree {
    	int data;
    	struct BitTree* LChild; //左子树
    	struct BitTree* RChild; //右子树
    }bittree;
    
    //创建二叉树
    bittree* createBitTree(bittree* BT) {
    	int num = 0;
    	scanf("%d", &num);
    	if (num != -1) {  //输入-1代表结束
    		BT = (bittree*)malloc(sizeof(bittree));
    		BT->data = num;
    		printf("输入%d的左结点值:", BT->data);
    		BT->LChild = createBitTree(BT->LChild);
    		printf("输入%d的右结点值:", BT->data);
    		BT->RChild = createBitTree(BT->RChild);
    	}
    	else {
    		BT = NULL; //输入-1,结点为NULL
    	}
    	return BT;
    }
    //先序遍历
    void PrePrint(bittree* BT) {
    	if (BT != NULL) {
    		printf("%d ", BT->data);
    		PrePrint(BT->LChild);
    		PrePrint(BT->RChild);
    	}
    	else { //结点为NULL,返回上一层
    		return;
    	}
    }
    
    
    //获取二叉树叶子节点个数
    int getLeaf(bittree* BT) {
    	int count;
    	if (BT == NULL) {
    		count = 0;
    	}
    	else if (BT->LChild == NULL && BT->RChild == NULL) {
    		count = 1;
    	}		
    	else {
    		count = getLeaf(BT->LChild) + getLeaf(BT->RChild);
    	}
    	return count;
    }
    
    void main() {
    	bittree* myBT = NULL;
    	myBT = createBitTree(myBT);
    	printf("先序遍历二叉树:
    ");
    	PrePrint(myBT);
    	printf("
    ");
    	printf("二叉树的叶子节点个数是:%d", getLeaf(myBT));
    }
    

  • 相关阅读:
    洛谷 U140360 购物清单
    洛谷 U140359 批量处理
    洛谷 U140358 操作系统
    洛谷U140357 Seaway连续
    洛谷 U141394 智
    洛谷 U141387 金
    CF1327F AND Segments
    刷题心得—连续位运算题目的小技巧
    CF743C Vladik and fractions
    洛谷 P6327 区间加区间sin和
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12775730.html
Copyright © 2011-2022 走看看