111. 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.

 

求根节点到叶子节点的距离,要求输出最小值

 

C++(13ms):

 1 /**
 2  * Definition for a binary tree node.
 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         if (root == NULL) return 0 ;
14         queue<TreeNode*> que ;
15         que.push(root) ;
16         int dep = 0 ;
17         while(!que.empty()){
18             int len = que.size() ;
19             dep++ ;
20             for(int i = 0 ; i < len ; i++){
21                 TreeNode* node = que.front() ;
22                 que.pop() ;
23                 if (node->left == NULL && node->right == NULL) 
24                     return dep ;
25                 if (node->left != NULL) 
26                     que.push(node->left) ;
27                 if (node->right != NULL) 
28                     que.push(node->right) ;
29             }
30         }
31     }
32 };

 

posted @ 2017-12-17 14:09  __Meng  阅读(169)  评论(0编辑  收藏  举报