Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
<思路>用递归的方法,如果有左子树,L+1;如果有右子树,R+1。最后返回深度。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
l = 1 + self.maxDepth(root.left) #left child tree depth
r = 1 + self.maxDepth(root.right) #right child tree depth
return max(l,r)
discuss里的BFS算法,学习借鉴。每次queue里存储一层的节点。
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
level = [root] if root else []
while level:
depth += 1
queue = []
for el in level:
if el.left:
queue.append(el.left)
if el.right:
queue.append(el.right)
level = queue
return depth