您的位置:首页 > 其它

LeetCode Minimum Depth of Binary Tree 最小深度二叉树

2013-11-06 08:02 453 查看
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.

本题思路:

1. 每进入一层用一个变量(这里是levelNum)记录当前从根节点到这一层节点的节点数

2. 当到达叶子节点的时候,就记录当前最小深度overall

2. 当所有的叶子节点都到达一遍之后,就得到了最终最小深度overall。

class Solution {
public:
	int minDepth(TreeNode *root) {
		if(root == nullptr) return 0;
		int overall = INT_MAX;
		int levelNum = 0;
		minD(root, overall, levelNum);
		return overall;
	}

	void minD(TreeNode *node, int &overall, int levelNum)
	{
		if(node == nullptr) return;
		levelNum++;
		minD(node->left, overall, levelNum);
		minD(node->right, overall, levelNum);
		if(node->left==nullptr && node->right==nullptr)
			overall = min(overall,levelNum);
	}
};


//2014-2-16 update
	int minDepth(TreeNode *root) 
	{
		if (!root) return 0;
		if (!root->left && !root->right) return 1;
		int L = root->left? minDepth(root->left)+1:INT_MAX;
		int R = root->right? minDepth(root->right)+1:INT_MAX;
		return min(L, R);
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐