码迷,mamicode.com
首页 > 其他好文 > 详细

543. 二叉树的直径 Diameter of Binary Tree

时间:2017-05-29 01:00:30      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:pretty   binary   efi   title   node   pre   following   empty   path   



  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int DiameterOfBinaryTree(TreeNode root) {
  12. if (root == null)
  13. return 0;
  14. /* get the height of left and right sub trees */
  15. int lheight = height(root.left);
  16. int rheight = height(root.right);
  17. /* get the diameter of left and right subtrees */
  18. int ldiameter = DiameterOfBinaryTree(root.left);
  19. int rdiameter = DiameterOfBinaryTree(root.right);
  20. /* Return max of following three
  21. 1) Diameter of left subtree
  22. 2) Diameter of right subtree
  23. 3) Height of left subtree + height of right subtree + 1 */
  24. return Math.Max(lheight + rheight, Math.Max(ldiameter, rdiameter));
  25. }
  26. /*The function Compute the "height" of a tree. Height is the
  27. number f nodes along the longest path from the root node
  28. down to the farthest leaf node.*/
  29. public int height(TreeNode node) {
  30. if (node == null)
  31. return 0;
  32. /* If tree is not empty then height = 1 + max of left
  33. height and right heights */
  34. return (1 + Math.Max(height(node.left), height(node.right)));
  35. }
  36. }






543. 二叉树的直径 Diameter of Binary Tree

标签:pretty   binary   efi   title   node   pre   following   empty   path   

原文地址:http://www.cnblogs.com/xiejunzhao/p/ac46feea266ab08377ddd3fff9b2c61e.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!