首页 > 学院 > 开发设计 > 正文

Leetcode 111 - Minimum Depth of Binary Tree(dfs)

2019-11-08 02:05:26
字体:
来源:转载
供稿:网友

github仓库:https://github.com/lzed/leetcode

题意

求二叉树的最短路径

思路

不同于求二叉树的最大路径在于:若当前节点有左节点但是没有右节点的时候,这时候只能对左节点进行递归。但是最大路径保证了对左右节点都进行递归的结果正确性,但是最小路径不能保证,必须要递归到叶子节点。

于是,我们每个节点分为如下3种情况:

NULL:返回0只有左节点或者右节点:统计有的那个节点的高度。没有左节点并且没有右节点:说明为leaf,递归结束,返回1。

代码

class Solution {public: int minDepth(TreeNode* root) { if (!root) return 0; if (!root->left && !root->right) return 1; return 1 + min(root->left ? minDepth(root->left) : 0x3e3e3e3e, root->right ? minDepth(root->right) : 0x3e3e3e3e); }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表