Leetcode_Minimum Depth of Binary Tree
来源:互联网 发布:php用apache还是nginx 编辑:程序博客网 时间:2024/06/05 11:24
题意为得出二叉树的最小深度,但深度是定义为从根节点到叶子节点的最少节点数。
容易出错的地方:为空节点时,直接返回0。这是不对的,要判断其是否有兄弟节点,没有兄弟节点的时候才能返回0,即这个节点的父节点是一个叶子节点。
错解1:
class Solution {public: int minDepth(TreeNode *root) {if(root==nullptr)return 0;return 1+min(minDepth(root->left),minDepth(root->right)); }};
错解2:
class Solution {public: int minDepth(TreeNode *root) {if(root==nullptr)return 0;if(root->left ==nullptr&&root->right==nullptr)return 1;return 1+(min(minDepth(root->left),minDepth(root->right))==0?max(minDepth(root->left),minDepth(root->right)):min(minDepth(root->left),minDepth(root->right))); }};<span style="color: rgb(169, 68, 66); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 18px; line-height: 19px; background-color: rgb(253, 253, 253);">Time Limit Exceeded</span>
正解:
class Solution {public: int minDepth(TreeNode *root) {if(root==nullptr)return 0;if(root->left ==nullptr&&root->right==nullptr)return 1;int lLen=minDepth(root->left);int rLen=minDepth(root->right);if(lLen&&rLen)//判断最小的那个是不是为0,为0的话,则是空节点,要以另一个节点的深度为准return 1+min(lLen,rLen);else{return 1+max(lLen,rLen);} }};错解2和正解,其实思路是一样的。但是错解2,由于没有设置中间变量,导致多次调用minDepth函数(即很长的那句代码,重复调用),导致超时。所以,写代码的时候,尤其要注意存储中间变量,避免没必要的多次函数调用。
0 0
- 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 (c++ and python version)
- Depth of binary tree
- Minimum Depth of Binary Tree,Maximum Depth of Binary Tree
- LeetCode: Depth of Binary Tree
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Maximum Depth of Binary Tree
- CPU电压的概念 VID Offset Load-Line Calibration
- SpringMVC数据类型转换
- Android 图片对比(图片相似度)代码
- 自定义圆形图片
- 仿新浪微博底部菜单TabHost
- Leetcode_Minimum Depth of Binary Tree
- 《算法导论》笔记(9) 动态规划 部分习题
- iOS xmpp之ejabberd服务器安装
- 面试题:请给出一段代码描述字符串写入文件
- TCP/IP 学习 (一)
- 《算法导论》笔记(10)贪心算法 部分习题
- SpringMVC数据格式化
- 基于核化相关滤波器的跟踪-效果直逼Struck和TLD跟踪器
- 简单的aes加密