/*** Definition for a binary tree node.* public class TreeNode {* public int val;* public TreeNode left;* public TreeNode right;* public TreeNode(int x) { val = x; }* }*/public class Solution {public int DiameterOfBinaryTree(TreeNode root) {if (root == null)return 0;/* get the height of left and right sub trees */int lheight = height(root.left);int rheight = height(root.right);/* get the diameter of left and right subtrees */int ldiameter = DiameterOfBinaryTree(root.left);int rdiameter = DiameterOfBinaryTree(root.right);/* Return max of following three1) Diameter of left subtree2) Diameter of right subtree3) Height of left subtree + height of right subtree + 1 */return Math.Max(lheight + rheight, Math.Max(ldiameter, rdiameter));}/*The function Compute the "height" of a tree. Height is thenumber f nodes along the longest path from the root nodedown to the farthest leaf node.*/public int height(TreeNode node) {if (node == null)return 0;/* If tree is not empty then height = 1 + max of leftheight and right heights */return (1 + Math.Max(height(node.left), height(node.right)));}}
543. 二叉树的直径 Diameter of Binary Tree
原文:http://www.cnblogs.com/xiejunzhao/p/ac46feea266ab08377ddd3fff9b2c61e.html