104. Maximum Depth of Binary Tree
Python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return self._travel(0, root)
def _travel(self, level, node):
if not node:
return level
return max(self._travel(level+1, node.left), self._travel(level+1, node.right))
Go
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return travel(0, root)
}
func travel(level int, node *TreeNode) int {
if node == nil {
return level
}
leftLevel := travel(level+1, node.Left)
rightLevel := travel(level+1, node.Right)
if leftLevel > rightLevel {
return leftLevel
} else {
return rightLevel
}
}
Javascript
var maxDepth = function(root) {
if (root === undefined) {
return 0
}
return travel(root, 0)
};
var travel = (node, level) => {
if (node === null) {
return level
}
return Math.max(travel(node.left, level+1), travel(node.right, level+1))
}