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.

 

Analyse: For the current node, minimum depth equals to 1 + min(depth of left subtree, depth of right subtree). We can do it recursively or iteratively.

1. Recursion

  New Version: 12ms

 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) return 0;
14         if(!root->left && !root->right) return 1;
15         
16         if(!root->left) return 1 + minDepth(root->right);
17         if(!root->right) return 1 + minDepth(root->left);
18         return 1 + min(minDepth(root->left), minDepth(root->right));
19     }
20 };

 

    Runtime: 12ms.

 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) return 0;
14         int leftDepth = minDepth(root->left);
15         int rightDepth = minDepth(root->right);
16         if(leftDepth == 0 && rightDepth == 0) return 1;
17         if(leftDepth == 0) leftDepth = INT_MAX;
18         if(rightDepth == 0) rightDepth = INT_MAX;
19         
20         return min(leftDepth, rightDepth) + 1;
21     }
22 };

 

2. Iteration: BFS. When it comes to a leaf node, then return its current depth.

    Runtime: 12ms.

 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) return 0;
14         
15         queue<TreeNode* > qu;
16         qu.push(root);
17         int level = 1;
18         while(!qu.empty()){
19             int n = qu.size();
20             while(n--){
21                 TreeNode* current = qu.front();
22                 qu.pop();
23                 if(!current->left && !current->right) return level;
24                 if(current->left) qu.push(current->left);
25                 if(current->right) qu.push(current->right);
26             }
27             level++;
28         }
29         return level;
30     }
31 };

 

posted @ 2015-07-31 15:40  amazingzoe  阅读(143)  评论(0编辑  收藏  举报