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. {
  12. Stack<TreeNode> S = new Stack<TreeNode>();//记录访问过的节点
  13.  
  14. Dictionary<TreeNode, List<TreeNode>> dic = new Dictionary<TreeNode, List<TreeNode>>();
  15.  
  16. private void postTree(TreeNode node)
  17. {
  18. if (node != null)
  19. {
  20. S.Push(node);
  21. if (node.left != null)
  22. {
  23. postTree(node.left);
  24. }
  25. if (node.right != null)
  26. {
  27. postTree(node.right);
  28. }
  29.  
  30. if (node.left == null && node.right == null)
  31. {
  32. var nodelist = S.ToList();
  33. nodelist.Reverse();
  34.  
  35. if (!dic.ContainsKey(node))
  36. {
  37. dic.Add(node, nodelist);
  38. }
  39. }
  40. S.Pop();
  41. }
  42. }
  43.  
  44. public int DiameterOfBinaryTree(TreeNode root)
  45. {
  46. postTree(root);
  47.  
  48. var maxDiameter = ;
  49.  
  50. foreach (var d in dic)
  51. {
  52. foreach (var d2 in dic)
  53. {
  54. if (d.Key == d2.Key)
  55. {
  56. var diameter = d2.Value.Count - ;
  57. maxDiameter = Math.Max(maxDiameter, diameter);
  58. }
  59. else
  60. {
  61. //第一种情况:计算叶子节点到根节点的直径
  62. var depth = d2.Value.Count - ;
  63.  
  64. var c1 = d.Value.Count;
  65. var c2 = d2.Value.Count;
  66. var diameter = ;
  67.  
  68. if (c1 < c2)
  69. {
  70. for (int i = ; i < c1; i++)
  71. {
  72. if (d.Value[i] != d2.Value[i])
  73. {
  74. diameter = c1 - i + c2 - i;
  75. break;
  76. }
  77. }
  78. }
  79. else
  80. {
  81. for (int i = ; i < c2; i++)
  82. {
  83. if (d.Value[i] != d2.Value[i])
  84. {
  85. diameter = c1 - i + c2 - i;
  86. break;
  87. }
  88. }
  89. }
  90.  
  91. //var IncCount = d.Value.Intersect<TreeNode>(d2.Value).Count();
  92. //var diameter = (c1 - IncCount) + (c2 - IncCount);
  93.  
  94. diameter = Math.Max(diameter, depth);
  95. maxDiameter = Math.Max(maxDiameter, diameter);
  96. }
  97. }
  98. }
  99. return maxDiameter;
  100. }
  101. }

https://leetcode.com/problems/diameter-of-binary-tree/#/description

补充一种递归的方式,使用python实现:

思路是每次递归判断,以当前节点为根节点是否能达到最大,见第14行。

而每次递归向上返回的是当前节点的左右子树的高度的更大的一个,加上当前节点(+1)的高度,见第15行。

  1. class Solution:
  2. def __init__(self):
  3. self.maxnum =
  4.  
  5. #隐含的前提,最大的距离应该是两个叶子节点的距离
  6. #本身这个函数是返回,当前节点到其所有叶子节点的最大深度
  7. def getLength(self,root):
  8. if root != None:
  9. #左子树的最大深度
  10. left = self.getLength(root.left)
  11. #右子树的最大深度
  12. right = self.getLength(root.right)
  13. #在返回之前,更新maxnum
  14. self.maxnum = max(self.maxnum,left+right)
  15. return + max(left,right)
  16. return
  17.  
  18. def diameterOfBinaryTree(self, root: 'TreeNode') -> 'int':
  19. self.getLength(root)
  20. return self.maxnum

这道题目与leetcode104 二叉树的最大深度,思想是一样的,可以说是104题的升级版。

leetcode543的更多相关文章

  1. [Swift]LeetCode543. 二叉树的直径 | Diameter of Binary Tree

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  2. LeetCode543. Diameter of Binary Tree

    Description Given a binary tree, you need to compute the length of the diameter of the tree. The dia ...

  3. Leetcode543.Diameter of Binary Tree二叉树的直径

    给定一棵二叉树,你需要计算它的直径长度.一棵二叉树的直径长度是任意两个结点路径长度中的最大值.这条路径可能穿过根结点. 示例 : 给定二叉树 1 / \ 2    3 / \ 4  5 返回 3, 它 ...

  4. LeetCode543.二叉树的直径

    题目 1 class Solution { 2 public: 3 int minimum = INT_MIN; 4 vector<int>res; 5 int diameterOfBin ...

  5. LeetCode树专题

    LeetCode树专题 98. 验证二叉搜索树 二叉搜索树,每个结点的值都有一个范围 /** * Definition for a binary tree node. * struct TreeNod ...

随机推荐

  1. L332 NBA: Dwyane Wade and Dirk Nowitzki Say Emotional Goodbyes

    Two games in the NBA ended amid emotional scenes on Tuesday as legends at separate teams marked thei ...

  2. 大大维的游戏机计划1--贪吃蛇v1

    本文为大大维原创,最早于博客园发表,转载请注明出处!!! 虽然本人一直是个免费的游戏测试员(/手动滑稽),但一直有着一个游戏架构师的梦想.正如马爸爸所说,梦想还是要有的,万一实现了呢? 这些天放寒假, ...

  3. 51单片机数据类型int,float,指针所占字节数

    1.int===2个字节 2.sfr===特殊功能寄存器,也是一种扩充数据类型,占用1个内存单元,利用它可以访问51单片机内的所有特殊功能寄存器. sfr P1 = 0x90;/////////这一句 ...

  4. getfacl

    ACL即Access Control List 主要的目的是提供传统的owner,group,others的read,write,execute权限之外的具体权限设置,ACL可以针对单一用户.单一文件 ...

  5. SignalTap导致PCIe Read/Write卡死

    /********************************************************************** * SignalTap导致PCIe Read/Write ...

  6. ubuntu 16 阿里云 vsftpd

    1.安装 apt-get install vsftpd 2.配置 conf vim /etc/vsftpd.conf --禁止匿名用户sed -i "s/anonymous_enable=Y ...

  7. LeetCode - Unique Email Addresses

    Every email consists of a local name and a domain name, separated by the @ sign. For example, in ali ...

  8. 第三章 jQuery总结 参考文本

    jQuery jQuery是javascript的一个函数库,非常方便,非常主流 利用jQuery开发步骤: 1导入jQuery库 2在$(function(){})的{}中编写jQuery代码 ①j ...

  9. xgboost实例代码

    # -*- coding: utf-8 -*- import xgboost as xgb import csv import jieba jieba.load_userdict('wordDict. ...

  10. 【java】接口

    class :用于定义类interface:用于定于接口 接口定义时,特点:1.接口中常见定义:常亮和抽象方法2.接口中的成员都有固定修饰符(如果没有会被隐式添加) 常量:public static ...