Minimum Depth of Binary Tree

Description:

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.

Code:

 1   int minDepth(TreeNode* root) {

 2         if ( root == NULL )

 3             return 0;

 4         else

 5         {

 6             if (root->left == NULL && root->right == NULL)

 7                 return 1;

 8             else if (root->left == NULL)

 9                 return 1+minDepth(root->right);

10             else if (root->right == NULL)

11                 return 1+minDepth(root->left);

12             else

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

14         }

15             

16     }

PS:  注意题目的说明,当结点root的其中一个孩子为空时,应当返回另一个孩子的最小深度,而不能直接返回1(1+0)。

你可能感兴趣的:(binary)