• 计算二叉树的深度和叶子数(递归)


    #include <stdio.h>
    typedef struct BiTNode
    {
    	char data;
    	struct BiTNode* rchild;
    	struct BiTNode* lchild;
    }BiTNode;
    //计算树的深度
    int TreeDepth(BiTNode *root)
    {
    	int right=0;
    	int left=0;
    	int deep=0;
    	if(root==NULL)
    	{
    		return deep;
    	}
    	right=TreeDepth(root->rchild);//计算左子树的深度
    	left=TreeDepth(root->lchild);//计算右子树的深度
    	deep=right>left?right:left;
    	deep++;
    	return deep;
    }
    //计算树的叶子树
    int TreeLeaf(BiTNode *root)//这里也可将叶子数传出.int TreeLeaf(BiTNode *root,int *num)
    {
    	static int num=0;
    	if(root==NULL)
    	{
    		return num;
    	}
    	if(root->lchild==NULL&&root->rchild==NULL)
    	{
    		num++;
    	}
    	TreeLeaf(root->lchild);
    	TreeLeaf(root->rchild);
    	return num;
    }
    int main()
    {
    	int deep=0;
    	int num=0;
    	BiTNode root={'O',NULL,NULL};
    	BiTNode a={'A',NULL,NULL};
    	BiTNode b={'B',NULL,NULL};
    	BiTNode c={'C',NULL,NULL};
    	BiTNode d={'D',NULL,NULL};
    	BiTNode e={'E',NULL,NULL};
    	root.lchild=&a;
    	root.rchild=&b;
    	a.lchild=&c;
    	a.rchild=&d;
    	d.rchild=&e;
    	deep=TreeDepth(&root);
    	printf("树的深度:%d
    ",deep);
    	num=TreeLeaf(&root);
    	printf("树的叶子数:%d
    ",num);
    }
    

      

  • 相关阅读:
    Vue 服务器端渲染(一)
    vue笔记 介绍及安装 一
    Node.js 学习笔记 (一) 安装配置
    Java开发中的23种设计模式详解(转)
    spring-boot整合ehcache实现缓存机制
    STM32流水灯
    SD卡封转及管脚说明
    随笔分类
    函数的设计之我见
    让灵魂追得上我们疲惫的身体
  • 原文地址:https://www.cnblogs.com/jueshi0208/p/5548936.html
Copyright © 2020-2023  润新知