leetcode编程记录9 #543 Diameter of Binary Tree
来源:互联网 发布:福禄克网络测试仪使用 编辑:程序博客网 时间:2024/05/18 01:29
leetcode编程记录9 #543 Diameter of Binary Tree
标签(空格分隔): leetcode
这次是一道关于树的题目,这是一个比较简单的题目,找出在树中的一条最长的路径的长度。题目如下:
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
题目理解与分析:
这道题目比较简单,只要实现求树的高度的函数,然后在递归调用该函数的过程中,存下最大路径,然后最后得到的就是一条最长路径。
代码如下:
class Solution {public: int diameterOfBinaryTree(TreeNode* root) { result = 0; if (root != NULL) { int example = height(root->left) + height(root->right); return max(example, result); } else { return 0; } }//private: int result; int max(int a, int b) { if (a > b) { return a; } else { return b; } } int height(TreeNode* root) { if (root == NULL) { return 0; } else { int left = height(root->left); int right = height(root->right); result = max(result, left + right); return max(left, right) + 1; } }};
阅读全文
0 0
- leetcode编程记录9 #543 Diameter of Binary Tree
- leetcode(543). Diameter of Binary Tree
- LeetCode 543 Diameter of Binary Tree
- 【Leetcode-easy-543】Diameter of Binary Tree
- Leetcode OJ contest24 543 Diameter of Binary Tree
- LeetCode OJ 543 Diameter of Binary Tree [Easy]
- Leetcode-543. Diameter of Binary Tree
- [leetcode] 543. Diameter of Binary Tree
- 【Leetcode】543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- leetcode-543. Diameter of Binary Tree
- leetcode-504-Diameter of Binary Tree
- leetcode-504-Diameter of Binary Tree
- [leetcode]-543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- (LeetCode) 543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- 索尼中国被判手机专利侵权,需赔偿910万元
- 突发 | 吴恩达确定将从百度离职 称赞李彦宏是AI领域最优秀CEO
- 刚才惊到我了,N年前自己在ITPub上的博客
- 196. Delete Duplicate Emails
- 装饰模式学习和思考
- leetcode编程记录9 #543 Diameter of Binary Tree
- MVC传值
- 网络编程-I/O复用服务器select/epoll/poll的使用基本概念
- 阿里云的“出海大戏”有哪些有趣看点?
- 卓正医疗战略合作腾爱医生 建立医疗服务新标杆
- 多灵亮相2017德国CeBIT,携手华为打造智能家居数字化时代
- 【JZOJ 5428】 查询
- Django环境搭建及一些常用命令
- Airbnb起了个中文名“爱彼迎” 还有比这更可怕的吗?