一、题目
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
二、代码实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
public class Solution {
int maxSum = 0;public int diameterOfBinaryTree(TreeNode root) {
int n = 0;if (root == null || (root.left == null && root.right == null)) {
return 0;}computeEdge(root);return maxSum;}public int computeEdge(TreeNode root) {
if (root == null) {
return 0;}int left = computeEdge(root.left);int right = computeEdge(root.right);if (left + right > maxSum) {
maxSum = left + right;}return left > right ? left + 1 : right + 1;}/*如果只计算根节点的左右节点的高度,然后返回两个数相加的和,但是有些情况并没有通过,是因为可能最长路径并不是通过根节点的,例如左孩子只有一个节点,但是右孩子的左右节点都很多,所以最后的方法是在计算二叉树的高度的时候比较左右子节点的高度的和与当前最长路径比较,最后返回最长路径*/
}
三、下面画图简单演示一下递归流程: