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

 

Hide Tags
 Tree Depth-first Search
 
    这题是找二叉树的最小深度,这是广度搜索比较好吧,为啥提示给的是 深度优先呢。
  1. 判断树是否为空
  2. 将root 节点压入队列
  3. while 队列不为空
  4. 计算当前队列的个数,进行这么多次的第5步
  5. 获取queue 头,弹出一个,判断弹出的时候为叶子,是的返回,不是将支点加入队列
 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 /**
 5  * Definition for binary tree
 6  */
 7  struct TreeNode {
 8      int val;
 9      TreeNode *left;
10      TreeNode *right;
11      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
12  };
13 
14 class Solution {
15 public:
16     int minDepth(TreeNode *root) {
17         if(root ==NULL) return 0;
18         queue<TreeNode* > qu;
19         TreeNode * curNode;
20         qu.push(root);
21         int ret =0;
22         while(!qu.empty()){
23             ret ++;
24             int n = qu.size();
25             while(n-->0){
26                 curNode =qu.front();
27                 qu.pop();
28                 if(curNode->left==NULL&&curNode->right==NULL)   return ret;
29                 if(curNode->left!=NULL) qu.push(curNode->left);
30                 if(curNode->right!=NULL)    qu.push(curNode->right);
31             }
32         }
33         return ret;
34     }
35 };
36 
37 int main()
38 {
39 
40     Solution sol;
41     return 0;
42 }
View Code

 

posted @ 2014-12-07 19:56  A_zhu  阅读(163)  评论(0编辑  收藏  举报