【Leetcode】【Easy】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.

 

递归的解题思路:

递归当前结点,分一下四种情况考虑:①结点为空时返回0;②结点没有右子树时,返回左子树最小值+1;③结点没有左子树时,返回右子树最小值+1;④当结点双子齐全时,返回左右子树的最小值+1;

注意:

1、注意判断“只有左子树”或“只有右子树”的情况,不要暴力的直接返回左/右子树最小值,因为有可能不存在;

2、省去了“当结点为叶子结点,则返回1”的情况,减少了代码行数,不过会多递归一层,运行时间没有变化;

 

 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         if (!root)
14             return 0;
15 
16         int minLeft = minDepth(root->left);
17         int minRight = minDepth(root->right);
18         
19         if (minLeft == 0) 
20             return minRight + 1;
21         else if (minRight == 0)
22             return minLeft + 1;
23         else return min(minLeft,minRight) + 1;
24     }
25 };

 

【★】迭代的解法:

用按层遍历二叉树的思想,当遍历到第一个叶子结点时,输出此时树的深度,则为最小depth。

用数组保存待遍历的树,设置双指针,一个指向访问当层开始的节点,一个指向访问当层结束节点的下一个位置。

 1 class Solution {
 2 public:
 3     int minDepth(TreeNode *root) {
 4         vector<TreeNode *> treeVec;
 5         treeVec.push_back(root);
 6         int cur = 0;
 7         int end;
 8         int depth = 0;
 9         
10         if (!root) 
11             return 0;
12         
13         while (cur < treeVec.size()) {
14             depth++;
15             end = treeVec.size();
16             while (cur < end) {
17                 if (!treeVec[cur]->left && \
18                     !treeVec[cur]->right) {
19                     return depth;    
20                 }
21                 
22                 if (treeVec[cur]->left) 
23                     treeVec.push_back(treeVec[cur]->left);
24                 
25                 if (treeVec[cur]->right) 
26                     treeVec.push_back(treeVec[cur]->right);
27                     
28                 cur++;
29             }
30         }
31     }
32 };

 

附录:

按层遍历二叉树

 

posted @ 2014-11-25 23:41  胡潇  阅读(286)  评论(0编辑  收藏  举报