LeetCode - Minimum Depth of Binary Tree

Minimum Depth of Binary Tree

2014/1/8 04:29

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.

Solution:

  The height of a tree is defined as the longest path from the root node down to the farthest leaf node. Here in this problem it's the opposite.

  The code below is simple enough to act as explanation for itself. An extra global variable is used to record the minimum depth during the recursive calls.

  Time complexity is O(n), where n is the number of nodes in the tree. Space complexity is O(1).

Accepted code:

 1 // 1WA, 1AC, good~
 2 /**
 3  * Definition for binary tree
 4  * struct TreeNode {
 5  *     int val;
 6  *     TreeNode *left;
 7  *     TreeNode *right;
 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9  * };
10  */
11 class Solution {
12 public:
13     // 1WA, only depths of leaf nodes count
14     int minDepth(TreeNode *root) {
15         // IMPORTANT: Please reset any member data you declared, as
16         // the same Solution instance will be reused for each test case.
17         if(root == nullptr){
18             return 0;
19         }
20         
21         result = INT_MAX;
22         _minDepth(root, 1);
23         return result;
24     }
25 private:
26     int result;
27     
28     const int &mymin(const int &x, const int &y) {
29         return (x < y ? x : y);
30     }
31     
32     int _minDepth(TreeNode *root, int depth) {
33         if(root->left == nullptr && root->right == nullptr){
34             if(depth < result){
35                 result = depth;
36             }
37         }
38         
39         if(root->left != nullptr){
40             _minDepth(root->left, depth + 1);
41         }
42         if(root->right != nullptr){
43             _minDepth(root->right, depth + 1);
44         }
45     }
46 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3510004.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值