package com.daily.daily20210131;
/**
* @Project: dailyCode
* @Site: http://www.zhao1iang.club/
* @Copyright: ©CodeLamp
* @Author: zhaoliang
* @Create: 2021-01-31 18:29
* @Desc: 二叉树的直径
**/
public class diameterOfBinaryTree {
// 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
this.val = x;
}
}
private int res;
public int diameterOfBinaryTree(TreeNode root){
res=1;
helper(root);
return res-1;
}
private int helper(TreeNode root) {
if(root==null)return 0;
int left = helper(root.left);
int right = helper(root.right);
res = Math.max(res,left+right+1);
return Math.min(left,right)+1;
}
}
日常刷题-二叉树的直径
最新推荐文章于 2022-05-10 16:13:13 发布