Diameter of a Binary Tree

Question

  1. The diameter of a tree (sometimes called the width) is the number of nodes
  2. on the longest path between two leaves in the tree.
  3. The diagram below shows two trees each with diameter nine,
  4. the leaves that form the ends of a longest path are shaded
  5. (note that there is more than one path in each tree of length nine,
  6. but no path longer than nine nodes).

Diameter of a Binary Tree

题解

和题 Lowest Common Ancestor 分析思路特别接近。

Java

  1. class TreeNode {
  2. int val;
  3. TreeNode left, right;
  4. TreeNode(int val) {
  5. this.val = val;
  6. this.left = null;
  7. this.right = null;
  8. }
  9. }
  10. public class Solution {
  11. public int diameter(TreeNode root) {
  12. if (root == null) return 0;
  13. // left, right height
  14. int leftHight = getHeight(root.left);
  15. int rightHight = getHeight(root.right);
  16. // left, right subtree diameter
  17. int leftDia = diameter(root.left);
  18. int rightDia = diameter(root.right);
  19. int maxSubDia = Math.max(leftDia, rightDia);
  20. return Math.max(maxSubDia, leftHight + 1 + rightHight);
  21. }
  22. private int getHeight(TreeNode root) {
  23. if (root == null) return 0;
  24. return 1 + Math.max(getHeight(root.left), getHeight(root.right));
  25. }
  26. public static void main(String[] args) {
  27. TreeNode root = new TreeNode(1);
  28. root.left = new TreeNode(2);
  29. root.right = new TreeNode(3);
  30. root.left.left = new TreeNode(4);
  31. root.left.right = new TreeNode(5);
  32. root.left.right.left = new TreeNode(6);
  33. root.left.right.left.right = new TreeNode(7);
  34. root.left.left.left = new TreeNode(8);
  35. Solution sol = new Solution();
  36. int maxDistance = sol.diameter(root);
  37. System.out.println("Max Distance: " + maxDistance);
  38. }
  39. }

Reference