zoukankan      html  css  js  c++  java
  • 计算二叉树的深度和叶子数(递归)

    #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
    多线程
    多进程进阶
    CentOS7中安装MySQL
    socket
    回顾
    Hibernate学习一:Hebinate入门以及一些小问题
    struts2学习二:Tomcat的部署目录和访问路径问题
    struts2学习一:hello struts2及struts2环境配置中遇到的问题
    Scanner几个问题与正则简介
  • 原文地址:https://www.cnblogs.com/jueshi0208/p/5548936.html
Copyright © 2011-2022 走看看