[面试真题] LeetCode: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.

分别考虑左右子树是否为空的情况并递归地进行计算。

Program Runtime: 60 milli secs

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int minDepth(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if(NULL == root){
16             return 0;
17         }
18         if(root->left != NULL && root->right == NULL){
19             return minDepth(root->left) + 1;
20         }else if(root->left == NULL && root->right != NULL){
21             return minDepth(root->right) + 1;
22         }else if(root->left == NULL && root->right == NULL){
23             return 1;
24         }else{
25             int left = minDepth(root->left);
26             int right = minDepth(root->right);
27             return 1 + (left < right ? left : right);
28         }
29     }
30 };

 

posted @ 2013-05-11 21:57  infinityu  阅读(380)  评论(0编辑  收藏  举报