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.