[LeetCode] Minimum Depth of Binary Tree

2014-11-24 01:44:11 · 作者: · 浏览: 1
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.
问题描述:给定一个二叉树,找到它的最小深度。最小深度定义为从根节点到最近的叶子节点的最短路径。
看到这个题,一般人可能会写出下面的代码:
int minDepth(TreeNode *root)  
{  
    if(root == NULL)  
        return 0;  
  
    int lh = minDepth(root->left);  
    int rh = minDepth(root->right);  
  
    return lh 
  

不过仔细想想,这段代码求的是什么呢?这段代码求的是节点的最低高度。直观的解释是节点的高度是左右孩子节点的深度的最小值,那得到的应该是节点的最小高度值。
本题要求的是根节点到最近的叶子节点的最短路径。那么,就可以用一个变量来跟踪叶子节点的层次,不过当左子树或者右子树为空时,就必须分开讨论了。
class Solution {  
public:  
    int minD(TreeNode *root, int lev)  
    {  
        if(root == NULL)  
            return lev;  
          
        if(root->left == NULL && root->right == NULL)  
            return lev;  
  
        if(root->left == NULL && root->right)  
            return minD(root->right, lev + 1);  
  
        if(root->left && root->right == NULL)  
            return minD(root->left, lev + 1);  
          
        int lh = minD(root->left, lev + 1);  
        int rh = minD(root->right, lev + 1);  
          
        return lh