Minimum Depth of Binary Tree

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.

 

#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int mindepth = INT_MAX;
void finddepth(TreeNode* curnode, int depth)
{
	if (curnode == NULL)
		return;
	if (!curnode->left&&!curnode->right){
		mindepth = depth+1 < mindepth ? depth+1 : mindepth;
		return;
	}
	finddepth(curnode->left, depth + 1);
	finddepth(curnode->right, depth + 1);
}
int minDepth(TreeNode *root) {
	if (root == NULL)
		return 0;
	finddepth(root, 0);
	return mindepth;
}


 

發佈了122 篇原創文章 · 獲贊 5 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章