111. 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.
方法一、递归的做法
要求:此题正好和Maximum Depth of Binary Tree一题是相反的,即寻找二叉树的最小的深度值:从根节点到最近的叶子节点的距离。
结题思路:和找最大距离不同之处在于:找最小距离要注意(l<r)? l+1:r+1的区别应用,因为可能存在左右子树为空的情况,此时值就为0,但显然值是不为0的(只有当二叉树为空才为0),所以,在这里注意一下即可!
int minDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if (leftDepth == 0)
return rightDepth + 1;
else if (rightDepth == 0)
return leftDepth + 1;
else
return min(leftDepth, rightDepth) + 1;
}
int minDepth(TreeNode* root) {
if(NULL == root)
return 0;
if(root->left == NULL)
return 1 + minDepth(root->right);
if(root->right == NULL)
return 1 + minDepth(root->left);
return 1 + min(minDepth(root->left),minDepth(root->right));
}
方法二、非递归的做法
level-order traversal and record current level depth, when meet a node which both child is null then return, no need to go farther
http://www.cnblogs.com/midhillzhou/p/6242613.html
或者见leetcode的top doscussion处