LeetCode 543 Diameter of Binary Tree
来源:互联网 发布:淘宝贷款15万交3000 编辑:程序博客网 时间:2024/06/08 06:00
题目:
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 ans = 0; int dfs(TreeNode* node) { if (!node) return 0; int left = dfs(node->left); int right = dfs(node->right); ans = max(ans, left + right); return 1 + max(left, right); } int diameterOfBinaryTree(TreeNode* root) { dfs(root); return ans; }};
阅读全文
0 0
- 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编程记录9 #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-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
- hibernate 中 createQuery与createSQLQuery 有什么区别?
- Itext获取PDF图层名称
- 框架学习系列 mybatis 第五篇 mybatis入门程序之需求开发2根据用户名模糊查询
- 通过js判断打开页面的手机浏览器类型
- 推荐一款好用的Visual Studio插件
- LeetCode 543 Diameter of Binary Tree
- java中Timer类的使用
- Java基础(一)
- html5-canvas基础API
- 1.Android硬件访问服务框架
- Android BroadcastReceiver之修改来电号码
- PAT 乙级 1004
- 模板不支持分离编译------原因以及解决方法
- 表格(table)隔行换色