问题:如题,求解树的直径,即树中两个节点的最长路径距离,该路径可能经过根节点,也可能不经过根节点
该题也是leetcode上的题,代码如下。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
getHeight(root);
return res;
}
public int getHeight(TreeNode node){
if(node == null)
return 0;
int left = getHeight(node.left);
int right = getHeight(node.right);
res = Math.max(res, left+right);
return 1+Math.max(left, right);
}
}