111. Minimum Depth of Binary Tree
来源:互联网 发布:ubuntu 安装iso文件 编辑:程序博客网 时间:2024/05/14 16:56
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.
最简单的思路是,递归调用minDepth函数,得到左右子树的minimum depth,然后作比较,取最小的depth.
但刚开始wrong answer了,后来发现返回值没有+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 ( root == NULL ) return 0; int left = minDepth(root->left); int right = minDepth(root->right); if ( root->left && !root->right ) return left+1;//这里注意+1 if ( root->right && !root->left ) return right+1; return left>right ? right+1 : left+1 ; }};
阅读全文
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
- 111.Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- Binary Tree Level Order Traversal
- 【附源码地址】Android高仿QQ及微信底部菜单的多种实现方式
- 第二周总结(二)
- LeetCode 141. Linked List Cycle
- 丑数
- 111. Minimum Depth of Binary Tree
- 了解百度云
- 配置和烧录LED闪烁例程
- 滴滴笔试编程题第一题
- JavaScript高级程序设计----读书笔记,第一、二章
- 还在疑惑并发和并行?
- 【BZOJ1419】Red is good 期望DP
- 机器人打高尔夫球
- Java的简单应用之插入排序和shell排序