LeetCode 543-二叉树的直径
题目描述:
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例:
给定二叉树

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
解答:
这道题是一个难度为简单的题目。开始的思路是只有经过根节点的路径才是最长的,那么这道题就是求根节点的左右子树的高度之和。于是代码如下:
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func diameterOfBinaryTree(root *TreeNode) int {
    /*
    var lhight, rhight = 0, 0
    if root == nil {
        return 0
    }
    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
}
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
    }
    return cnt+1
}
但是最后并没有通过,无法通过下面这组用例。

正确的结果应该是8对应的是 [-1 0 6 9 -9 -7 -6 9 -2] 这条路径。

正确的方法是结合求二叉树高度的思路,我们只需要在求二叉树高度的代码中加入求最长路径的代码就可以了。
/**
 * 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
}
总结:
这道题并不难,但是我做了很久,主要是一开始的思路是错误的,然后我对二叉树的高度是如何求的也不是很熟悉,更多的是我的拖延和懒惰导致的。下次要注意。

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号