111. Minimum Depth of Binary Tree

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.

即这道题要求找出二叉树中根节点到最近一个叶节点的距离。

问题分析:

由于题目给出的树是一颗二叉树,那么整个问题就简单化了。我们只需要思考以下几种情况就好:①这个树为空,那么距离当然为0;②这个树只有一个根节点,那么距离为1;③这个树存在叶节点。第三种情况相对复杂一些,我们把情况细化,可以分解为,一个父节点到叶节点的最小距离,可以由其子节点到叶节点的最小距离得到。其中,父节点到叶节点的最小距离,为其左节点到叶节点的最小距离与其右节点到叶节点的最小距离直接的比较,取较小值加1.

那么,这道题可以用递归的方式求解。给出递归的终结条件(即该节点为空或者该节点为叶节点),按照第三种情况的关系实现即可。

代码:

 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  #include <queue>
11 class Solution {
12 public:
13     int minDepth(TreeNode* root) {
14        if(!root) return 0;
15        if(!root->left && !root->right) return 1;
16        int left = minDepth(root->left);
17        int right = minDepth(root->right);
18        if(left == 0)
19        return right + 1;
20        if(right == 0)
21        return left + 1;
22        return left<right?left+1:right+1;
23     }
24 };

 

转载于:https://www.cnblogs.com/MT-ComputerVision/p/6985854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值