122 - 543 二叉树的直径

题目

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 : 给定二叉树

      1
     / \
    2   3
   / \     
  4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

解答

https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/javade-di-gui-jie-fa-by-lyl0724-2/

一个节点最大直径,就是左树高度+右树高度。

也就是求每个节点最大直径,从中取最大值

https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/goyu-yan-jian-dan-yi-dong-by-yu-ting-2/

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
func diameterOfBinaryTree(root *TreeNode) int {
    if root == nil {
        return 0
    }
    m := 0
    depth(root, &m)
    return m
}
func depth(root *TreeNode, m *int) int {
    if root == nil {
        return 0
    }
    l := depth(root.Left, m)
    r := depth(root.Right, m)
    *m = int(max(l+r, *m))
    return int(max(l, r)) + 1
}

Runtime: 4 ms, faster than 95.31% of Go online submissions for Diameter of Binary Tree.

Memory Usage: 4.5 MB, less than 100.00% of Go online submissions for Diameter of Binary Tree.

var diameterOfBinaryTree = function(root) {
  if (!root) {
    return 0
  }
  let m = 0
  const depth = function(root) {
    if (!root) {
      return 0
    }
    const l = depth(root.left)
    const r = depth(root.right)
    m = Math.max(l + r, m)
    return Math.max(l, r) + 1
  }
  depth(root)
  return m
};

Runtime: 64 ms, faster than 68.25% of JavaScript online submissions for Diameter of Binary Tree.

Memory Usage: 37.1 MB, less than 75.00% of JavaScript online submissions for Diameter of Binary Tree.

class Solution:
    def __init__(self):
        self.ans = 0

    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        if not root:
            return 0
        self.depth(root)
        return self.ans

    def depth(self, root: TreeNode) -> int:
        if not root:
            return 0
        l = self.depth(root.left)
        r = self.depth(root.right)
        self.ans = max(l+r, self.ans)
        return max(l, r)+1

Runtime: 56 ms, faster than 44.95% of Python3 online submissions for Diameter of Binary Tree.

Memory Usage: 16 MB, less than 48.28% of Python3 online submissions for Diameter of Binary Tree.

Last updated

Was this helpful?