算法作业_37(2017.6.19第十八周)
来源:互联网 发布:sublime json 格式化 编辑:程序博客网 时间:2024/06/05 12:44
104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question.
111. Minimum Depth of Binary Tree
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.
Subscribe to see which companies asked this question.
解析:这是两道相似的二叉树递归问题,但是测试用例还是存在一些差别。如111最小的长度,如果一棵树只有一颗子树,那么最短长度不是0 也不是1,而是子数的最短长度。
Maximum Depth of Binary Tree:
/** * 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 maxDepth(TreeNode* root) { if(root == NULL) return 0; int leftMax = maxDepth(root->left); int rightMax = maxDepth(root->right); return max( leftMax , rightMax) +1; }};
Minimum Depth of Binary Tree
/** * 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 = 0, right = 0 ; if(root->left == NULL){ return minDepth(root->right)+1; } if(root->right ==NULL){ return minDepth(root->left)+1; }else{ left = minDepth(root->left); right = minDepth(root->right); } return min(left, right)+1; }};
阅读全文
0 0
- 算法作业_37(2017.6.19第十八周)
- 算法作业_38(2017.6.20第十八周)
- 算法作业_39(2017.6.21第十八周)
- 算法作业_40(2017.6.22第十八周)
- 算法作业_41(2017.6.24第十八周)
- 算法第十八周作业01
- 第十八周作业 1.0
- 算法设计与结构基础作业第十八周
- 算法课第十八周作业 | Course Schedule II
- 算法课第十八周Same Tree
- leetcode第十八周解题总结-贪心算法
- 第十八周
- 第十八周
- 第十八周算法分析与设计:Add Two Numbers
- 算法作业_25(2017.6.1第十五周)
- 算法作业_26(2017.6.6第十六周)
- 算法作业_27(2017.6.8第十六周)
- 算法作业_28(2017.6.8第十六周)
- servlet生命周期与/filter/listener/interceptor区别与联系
- leetcode | 按层访问一棵二叉树 | Python
- 计算机图形学----DDA、Bresenham直线算法
- jfinal 多数据源 Db+record 分页
- SetFileCompletionNotificationModes FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
- 算法作业_37(2017.6.19第十八周)
- Android UI测试框架Espresso以及代码覆盖率jacoco的使用
- npm常用命令
- 接续符和转义符
- DPCM编解码
- 【脚本语言系列】关于Python数据库处理SQLAlchemy,你需要知道的事
- NodeJs新手入门(三)
- JAVA基础IO-fileReader字符流
- 关于STL中的堆栈Stack