[leetcode]: 543. Diameter of Binary Tree
来源:互联网 发布:光纤交换机端口 编辑:程序博客网 时间:2024/06/06 13:22
1.题目
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.
翻译:给定一棵二叉树,求该树上两个节点之间最长距离
2.分析
例子中最长距离其实是左子树深度+右子树深度。
另一种情况是:
1 / \ 2 3 / \ 4 5 / \ / \6 7 8 9/ \ / \11 12 13 14
最长距离出现在11-14
拓展到一般情况:最长距离为这棵树及其所有子树的最长距离的最大值。
3.代码
int diameterOfBinaryTree(TreeNode* root) { if (root == NULL) return 0; return max(getTreeHeight(root->left) + getTreeHeight(root->right), max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right))); }int getTreeHeight(TreeNode* root) { if (root == NULL) return 0; return 1 + max(getTreeHeight(root->left), getTreeHeight(root->right));}
阅读全文
0 0
- 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]-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: Python]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 (Java)
- Leetcode-543. Diameter of Binary Tree
- iOS 允许HTTP请求
- 1.jQuery 入门
- OpenStack服务开机自启动
- PCM转WAV格式 Wav数据格式的44个字节头部信息汇总
- Oracle select case when
- [leetcode]: 543. Diameter of Binary Tree
- c++ 操作系统实验 进程调度
- nginx在windows下配置反向代理
- lua——赢三张牌型处理相关算法(下)——牌型比较
- POI导出工具类
- [蓝桥杯] 历届试题 剪格子(dfs+回溯)
- Hello cocos2d-x!
- java实现冒泡排序
- java导出Excel表格