直径就是,最大的 两个节点之间的距离。
最大的距离必然存在于某个节点的左右子树之间,这样说来,距离其实也就是左右子树的最大深度之和。所以只要在求最大深度的过程中,即后序遍历时,找到最大的左右子树深度之和就好啦。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
private int result = 0;
public int diameterOfBinaryTree (TreeNode root) {
if (root == null) {
return 0;
}
depth(root);
return result;
}
private int depth(TreeNode root) {
if (root == null) {
return 0;
}
int left = depth(root.left);
int right = depth(root.right);
if (left + right > result) {
result = left + right;
}
return Math.max(left, right) + 1;
}
}

京公网安备 11010502036488号