leetcode dfs Minimum Depth of Binary Tree

Minimum Depth of Binary Tree

 Total Accepted: 25609 Total Submissions: 86491My Submissions

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.




题意:求出二叉树的最小深度
思路:

minDepth(root) = 1 + min(minDepth(root->left), minDepth(root->right));

但假设 root -> left 或 root->right为空时,minDepth对他们的计算结果为返回 0 ,所以这两个要分别处理一下。


复杂度: 时间O(n) 。空间O(log n)


int minDepth(const TreeNode *root){
	if(!root) return 0;
	if(!root->left) return 1 + minDepth(root->right);
	if(!root->right) return 1 + minDepth(root->left);
	return 1 + min(minDepth(root->left), minDepth(root->right));
}


posted on 2017-06-14 14:39  wgwyanfs  阅读(83)  评论(0编辑  收藏  举报

导航