题目链接:LeeCode543二叉树的直径
题目描述:
求树中两个节点最远的距离,不一定过根节点,我直接想的思路就是通过最大深度,某个点左右子树最大深度和肯定有最远的,然后思路对了就开写,真是过年过傻了,竟然将节点遍历出来再挨个求深度,最后想到可以求深度的过程中解决问题
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private static int ans=0;
public static int diameterOfBinaryTree(TreeNode root) {
if(root==null||(root.left==null&&root.right==null))return 0;
ans=0;
TreeDeep(root);
return ans;
}
public static int TreeDeep(TreeNode root){
if(root==null)return 0;
//求出左,右节点的深度
int l=TreeDeep(root.left);
int r=TreeDeep(root.right);
//每次记录所有中最长的
ans=Math.max(l+r,ans);
return Math.max(l,r)+1;
}
}