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.

寻找一棵树的最短路径的深度。

 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     void dfs(TreeNode *root,int &MIN,int step)
13     {
14          if(root==NULL) return ;
15          if(root->left==NULL && root->right==NULL)
16          {
17              if(MIN>step) MIN=step;
18              return ;
19          }
20          dfs(root->left,MIN,step+1);
21          dfs(root->right,MIN,step+1);
22     }
23     int minDepth(TreeNode *root) {
24         if(root==NULL) return 0;
25         int MIN=9999999;
26         dfs(root,MIN,1);
27         return MIN;
28     }
29 };

如果树没有节点,那么返回0.否则的话,构造一个dfs函数。递归进行查找,

posted on 2015-04-26 21:44  何氏小萌  阅读(149)  评论(0)    收藏  举报