C語言實現二叉樹根節點到葉子節點的最小距離

直接上代碼

#include<stdio.h>

typedef struct TreeNode
{
	int data;
	struct TreeNode * lchild;
	struct TreeNode * rchild;
}TreeNode;

//根節點到葉子結點的最小的距離
int minDepth(TreeNode * root)
{
	if (root == NULL)
	{
		return 0;
	}

	//如果是葉子結點則返回
	if (root->lchild == NULL && root->rchild == NULL) //葉子結點
	{
		return 1;
	}

	int minleft = 0;
	int minright = 0;
	int mindepth = 0;

	//如果存在左子樹則計算左子樹的最小深度
	if (root->lchild != NULL)  
	{
		minleft = minDepth(root->lchild) + 1;
	}
	//如果存在右子樹則計算左子樹的最小深度
	if (root->rchild != NULL)
	{
		minright = minDepth(root->rchild) + 1;
	}

	if (root->rchild == NULL)
	{
		mindepth = minleft; //如果只存在左子樹則計算左子樹的最小深度,最小深度爲左子樹
	}
	else if (root->lchild == NULL)
	{
		mindepth = minright; //如果只存在右子樹則計算左子樹的最小深度,最小深度爲右子樹
	}
	else
	{
		mindepth = minleft < minright ? minleft : minright; //如果左右子樹都存在,爲其中最小的
	}

	return mindepth;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章