Tencent 37-Maximum depth of binary tree # leetcode104
Given a binary tree, find its maximum depth.
The depth of the binary tree is the number of nodes on the longest path from the root node to the furthest leaf node.
Explanation: A leaf node refers to a node that has no child nodes.
Example:
Given a binary tree [3,9,20, null, null, 15,7],
3
/
920
/
157
returns to its maximum depth 3.
Recursive function, 2 lines of code:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:return 0
return max(1+self.maxDepth(root.left),1+self.maxDepth(root.right))