Diameter of Binary Tree问题及解法
来源:互联网 发布:数据库笛卡尔积运算 编辑:程序博客网 时间:2024/05/20 23:05
问题描述:
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.
示例:
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].
问题分析:求解该问题实际是就是求解树的深度问题,两棵子树深度求解完成,相应的的答案也就出来了。
过程详见代码:
/** * 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 diameterOfBinaryTree(TreeNode* root) { int diameter = 0; height(root, diameter); return diameter; }private: int height(TreeNode* node, int& diameter) { if (!node) { return 0; } int lh = height(node->left, diameter); int rh = height(node->right, diameter); diameter = max(diameter, lh + rh); return 1 + max(lh, rh); }};
0 0
- Diameter of Binary Tree问题及解法
- Diameter of Binary Tree
- Diameter of Binary Tree
- Diameter of Binary Tree
- Diameter of Binary Tree
- Diameter of Binary Tree
- leetcode[Diameter of Binary Tree]//待整理多种解法
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- LeetCode543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- Android 8.0后台执行限制
- Python语言的优点和缺点
- 【脚本语言系列】关于PythonGUI界面PythonWin,你需要知道的事
- struts2使用注意点
- RecyclerView优雅的刷新
- Diameter of Binary Tree问题及解法
- hadoop搭建测试版
- 更好的学习与记忆
- Spring注解@Component、@Repository、@Service、@Controller区别
- CNN文本分类 论文收集
- 深度学习Deeplearning4j 入门实战(2):Deeplearning4j 手写体数字识别Spark实现
- iOS常用的宏
- Java原生JNI的使用、javah指令的使用以及图解教材
- 单向循环链表