题目描述
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
解题思路
1、题意理解:求二叉树的直径,如上图示例可知,我们看作节点1的左子树的深度 + 节点1的右子树的深度
2、代码逻辑:使用递归求出任意节点的最大深度,并且记录(L+R)的最大值
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxdepth(root);
return max;
}
public int maxdepth(TreeNode root){
if(root == null)
return 0;
int L = maxdepth(root.left);
int R = maxdepth(root.right);
max = Math.max(max, L + R);
return Math.max(L, R) + 1;
}
}
参考:https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/Java-Solution-MaxDepth
https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/shi-pin-jie-shi-di-gui-dai-ma-de-yun-xing-guo-chen/