14.Diameter of Binary Tree(二叉树的直径)
Posted yjxyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了14.Diameter of Binary Tree(二叉树的直径)相关的知识,希望对你有一定的参考价值。
Level:
??Easy
题目描述:
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.
思路分析:
??题目要求找出二叉树的直径,二叉树的直径的定义是,任意两节点之间的最长路径,这个路径不一定会经过根节点。我们的解题思路是,最长路径肯定是以某个节点为中转,分别从这个节点的左右子节点延伸到叶子节点的两条无转向的路径和。所以只需要求出所有节点作为中转节点的路径长度,取其中最大的就得到了答案。
代码:
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x){
val=x;
}
}
public class Solution{
public int diameterOfBinaryTree(TreeNode root){
if(root==null)
return 0;
int res=depth(root.left)+depth(root.right);
int ledia=diameterOfBinaryTree(root.left);
int ridia=diameterOfBinaryTree(root.right);
return Math.max(Math.max(res,ledia),ridia);
}
public int depth(TreeNode root){
if(root==null)
return 0;
int left=depth(root.left);
int right=depth(root.right);
return Math.max(left,right)+1;
}
}
以上是关于14.Diameter of Binary Tree(二叉树的直径)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 110. Balanced Binary Tree
[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree