LeetCode 111. Minimum Depth of Binary Tree
来源:互联网 发布:windows 高精度sleep 编辑:程序博客网 时间:2024/04/20 23:32
题目:
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.
思路:
找出最小深度,最小深度是叶节点到根节点的最短路径,如果根节点没有叶节点,返回1,如果根节点只有左节点 ,返回 minDepth(root->left)+1;如果根节点只有右节点,返回minDepth(root->right)+1;如果都有,返回两个中小的。
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode* root) { if(NULL==root){//如果根节点为NULL,返回0 return 0; } else if(root->left==NULL&&root->right==NULL){//如果根节点没有叶节点,返回1 return 1; } else if(root->left!=NULL&&root->right==NULL){//如果根节点只有左节点 return minDepth(root->left)+1; } else if(root->left==NULL&&root->right!=NULL){//如果根节点只有右节点 return minDepth(root->right)+1; } else{//如果左右节点都有 return min(minDepth(root->left)+1,minDepth(root->right)+1); } }};
**输出结果:**9ms
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- IT404过关游戏WP
- The method getContextPath() from the type HttpServletRequest refers to the missing type
- Hexo NexT 主题下 blockquote 文本内容超出不自动换行解决方式
- 背包九讲
- 2017 蓝桥杯JavaB组省赛 日期问题
- LeetCode 111. Minimum Depth of Binary Tree
- Leetcode-549. Binary Tree Longest Consecutive Sequence II
- Vue2.0进阶组件篇4 突如其来(时间倒计时组件)
- 静态二维数组和动态二维数组(C语言)
- 170408 汇编-段内转移指令
- Unity3D游戏记录回放插件EZReplayManager(三)
- Windows 10中的PowerShell内置运行软件版本
- 谈谈我对云计算的认识之基本概念(二)
- LeetCode 226. Invert Binary Tree