您的位置:首页 > 其它

Minimum Depth of Binary Tree【leetcode】

2014-10-18 16:38 218 查看
Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

递归。

考虑5种情况,

1.节点为空

2.节点不为空,且左右儿子节点也不为空

3,右儿子节点为空

4,左儿子节点为空

5,左右儿子都为空

int minDepth(TreeNode *root) {
	if (root == NULL)
		return 0;
	int a=0, b=0;
	if (root->left &&root->right){
		a = minDepth(root->left) + 1;
		b = minDepth(root->right) + 1;
		return a < b ? a : b;
	}else
	if (root->left && root->right==NULL){
		return 1 + minDepth(root->left);
	}else
	if (root->right && root->left==NULL){
		return 1 + minDepth(root->right);
	}else
	if (root->left == NULL && root->right == NULL){
		return 1;
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: