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
1
/
2 3
/
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
return helper(root.left) + helper(root.right);
我想的是:在主函数中调用递归
我去。。和正确答案的分歧好严重。。
首先,这种【计算题】还是用DC为主。DC需要在helper函数内部,主函数就一个调用就行了。
怎么保证是最长路径呢?就直接左右递归就行了吧我觉得。比较得用max
max是全局变量、维持结果return left right中最长的一端优势,这是这道题的特色
还是原来的traverse相加的思路,就是不记得用DC了
做了2遍还是对思路毫无印象啊,得彻彻底底理解才能记住
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { //cc if (root == null) return 0; getLength(root); return max; } int getLength(TreeNode root) { //cc if (root == null) return 0; int left = getLength(root.left); int right = getLength(root.right); max = Math.max(max, left + right); return Math.max(left, right) + 1; } }