LeetCode | Minimum Depth of Binary Tree
来源:互联网 发布:淘宝店铺装修添加宝贝 编辑:程序博客网 时间:2024/06/06 09:51
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
如下图:
应当返回的值是2.但是如果类似于求树的高度,直接使用min(left,height)+1会导致返回的值始终是1
因为在这个时候右子树为空,左子树不为空(2),最近的叶子节点还在左侧。
class Solution {public: int minDepth(TreeNode* root) { if(!root) return 0; int left=minDepth(root->left); int right=minDepth(root->right); //表示已经找到叶子节点 if(left==0 && right==0) return 1; //如果二者只有一个为0,则表示其中一棵子树为空 //故这棵为空的子树的高度不应当算给整体高度,而应当单独处理 if(left==0) return right+1; if(right==0) return left+1; return min(left,right)+1; }};
0 0
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- Linux各目录的作用
- 在线实时大数据平台Storm并行和通信机制理解
- Dubbo服务分组
- DOM基础
- SoundPool类-游戏中即时音效的简介
- LeetCode | Minimum Depth of Binary Tree
- 【HDU1847】Good Luck in CET-4 Everybody!(博弈)
- iOS--获取当前视图控制器
- UCOSIII信号量和互斥信号量
- 使用C# .net开发微信公众号之获取AccessToken
- bitbake 入门学习之helloworld
- Linux常用命令大全
- Codeforces Round #366 (Div. 2)题解报告
- java梭哈的小游戏