543. Diameter of Binary Tree | 二叉树的“直径”
来源:互联网 发布:淘宝买的东西下架了 编辑:程序博客网 时间:2024/06/07 14:52
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.
Subscribe to see which companies asked this question.
思路:先用的方法是只计算根节点的左右节点的高度,然后返回两个数相加的和,但是发现有些情况并没有通过,是因为可能最长路径并不是通过根节点的,例如左孩子只有一个节点,但是右孩子的左右节点都很多,所以最后的方法是在计算二叉树的高度的时候比较左右子节点的高度的和与当前最长路径比较,最后返回最长路径。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { int maxNum = 0;public int diameterOfBinaryTree(TreeNode root) {int n = 0;if (root == null || (root.left == null && root.right == null)) {return 0;}helper(root);return maxNum;}public int helper(TreeNode root) {if (root == null) {return 0;}int left = helper(root.left);int right = helper(root.right);if (left + right > maxNum) {maxNum = left + right;}return left > right ? left + 1 : right + 1;}}
0 0
- 【二叉树】树的直径【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 二叉树的直径
- [LeetCode]543. Diameter of Binary Tree(计算二叉树的直径的长度)
- leetcode解题之543. Diameter of Binary Tree Java版 (二叉树的最大直径)
- 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
- 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
- 543. Diameter of Binary Tree
- 【设计模式】新手入门笔记
- C++ Primier学习笔记2-虚函数
- 记录下我的第一篇博客
- 抓取手机数据网络的网络包(一)——安装adb,并pc连接手机
- css js实现3D魔方转动
- 543. Diameter of Binary Tree | 二叉树的“直径”
- C++类成员初始化列表
- 将tensorflow训练的model,转换为.pb格式的model
- Eclipse项目迁移为Android Studio项目步骤及注意事项
- centos7安装redis3.2.8
- T440s的supervisor Pwd和Power-On Pwd
- 433-最长的单词
- MySQL数据库结构优化(一)
- pod search找不到自己trunk push的库的解决方法