二叉树的直径
2021-01-20 本文已影响0人
windUtterance
题目描述:
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例:
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
作者:tuo-jiang-de-ye-ma-2
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/cu-su-yi-dong-kan-zhu-jie-zhi-xing-yong-shi-0-ms-z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) return 0;
getMaxDep(root);
return res;
}
private int getMaxDep(TreeNode curRoot) {
if(curRoot == null) return 0;
int leftDep = getMaxDep(curRoot.left);
int rightDep = getMaxDep(curRoot.right);
if(leftDep + rightDep > res) res = leftDep + rightDep;
return Math.max(leftDep, rightDep) + 1;
}
}