代码改变世界

leetcode - Minimum Depth of Binary Tree

2017-08-13 08:48  tlnshuju  阅读(139)  评论(0编辑  收藏  举报

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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
    int minDepth(TreeNode *root) {
		min = INT_MAX;
		dfs(root,1);
		return min;
    }
private:
	int min;
	void dfs(TreeNode *root,int level)
	{
		if(root == NULL) return ;
		if(root->left == NULL && root->right == NULL)
		{
			if(level < min) min = level;
		}
		else
		{
			dfs(root->left,level+1);
			dfs(root->right,level+1);
		}
	}
};