题目描述:
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例:
给定二叉树
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
解答:
这道题是一个难度为简单的题目。开始的思路是只有经过根节点的路径才是最长的,那么这道题就是求根节点的左右子树的高度之和。于是代码如下:
go;gutter:true;
/**
* Definition for a binary tree node.</p>
<ul>
<li>type TreeNode struct {</li>
<li>Val int</li>
<li>Left *TreeNode</li>
<li>Right *TreeNode</li>
<li>}
*/</li>
</ul>
<p>func diameterOfBinaryTree(root <em>TreeNode) int {
/</em>
var lhight, rhight = 0, 0
if root == nil {
return 0
}</p>
<pre><code>if root.Left != nil {
lhight = calHeight(root.Left)
}
if root.Right != nil {
rhight = calHeight(root.Right)
}
if lhight > rhight {
return lhight + rhight
} else {
return rhight + lhight
}
return 0
</code></pre>
<p>}</p>
<p>func calHeight(root *TreeNode) int {
if root == nil {
return 0
}</p>
<pre><code>cnt := 0
lh := calHeight(root.Left)
rh := calHeight(root.Right)
if lh > rh {
cnt = lh
} else {
cnt = rh
}
return cnt+1
</code></pre>
<p>}</p>
<pre><code>
但是最后并没有通过,无法通过下面这组用例。
![LeetCode 543-二叉树的直径](https://johngo-pic.oss-cn-beijing.aliyuncs.com/articles/20230605/695616-20200201185741522-1759254025.png)
正确的结果应该是8对应的是 [-1 0 6 9 -9 -7 -6 9 -2] 这条路径。
![LeetCode 543-二叉树的直径](https://johngo-pic.oss-cn-beijing.aliyuncs.com/articles/20230605/695616-20200201191309352-2016614757.png)
正确的方法是结合求二叉树高度的思路,我们只需要在求二叉树高度的代码中加入求最长路径的代码就可以了。
;gutter:true;
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var res int
func diameterOfBinaryTree(root *TreeNode) int {
res = 1 //初始的路径长度
calHeight(root)
return res-1
}
func calHeight(root *TreeNode) int {
if root == nil {
return 0
}
cnt := 0
lh := calHeight(root.Left) //左子树的长度
rh := calHeight(root.Right) //右子树的长度
if lh > rh {
cnt = lh
} else {
cnt = rh
}
if res < lh + rh + 1 { //lh+rh+1是本次遍历的路径的长度
res = lh + rh + 1 //更新res
}
return cnt+1
}
总结:
这道题并不难,但是我做了很久,主要是一开始的思路是错误的,然后我对二叉树的高度是如何求的也不是很熟悉,更多的是我的拖延和懒惰导致的。下次要注意。
Original: https://www.cnblogs.com/dennis-wong/p/12249885.html
Author: 成蹊0xc000
Title: LeetCode 543-二叉树的直径
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/582790/
转载文章受原作者版权保护。转载请注明原作者出处!