给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
二叉树的直径不一定过根节点,因此需要去搜一遍所有子树(例如以root,root.left, root.right…为根节点的树)对应的直径,取最大值。
root的直径 = root左子树高度 + root右子树高度
root的高度 = max {root左子树高度, root右子树高度} + 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
//使用dfs
class Solution {
int max=0;
public int dfs(TreeNode root){
if(root==null){
return 0;
}
int left = dfs(root.left);
int right = dfs(root.right);
max = Math.max(left+right,max);
return Math.max(left,right)+1;
}
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);
return max;
}
}