【leetcode】Minimum Depth of Binary Tree (easy)

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.

 

简单题,不过注意叶子结点是两个子树都是NULL的指针。只有一个子树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) {
        if(root == NULL)
        {
            return 0;
        }

        if((root->left == NULL)&&(root->right == NULL))
        {
            return 1;
        }
        else if(root->left == NULL)
        {
            return minDepth(root->right) + 1;
        }
        else if(root->right == NULL)
        {
            return minDepth(root->left) + 1;
        }
        else 
        {
            return min(minDepth(root->left), minDepth(root->right)) + 1;
        }
    }
};

 

posted @ 2014-11-23 13:08  匡子语  阅读(187)  评论(0编辑  收藏  举报