给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
返回它的最大深度 3 。
先来说迭代,依然是用队列。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def maxDepth(self, root: TreeNode) -> int:
que=deque()
if not root:
return 0
elif not root.left and not root.right:
return 1
else:
que.append([1,root])
d=0
while que:
depth,p=que.popleft()
if p:
que.append([depth+1,p.left])
que.append([depth+1,p.right])
d=max(d,depth)
return d
再来说递归
# 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 find_depth(self,p1,p2,l1):
if not p1 and not p2:
return l1
if not p1:
l1+=1
return self.find_depth(p2.left,p2.right,l1)
elif not p2:
l1+=1
return self.find_depth(p1.left,p1.right,l1)
else:
l1+=1
l2=self.find_depth(p1.left,p1.right,l1)
l3=self.find_depth(p2.left,p2.right,l1)
return max(l2,l3)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.right and not root.left:
return 1
l1=l2=1
while root:
l1=self.find_depth(root.left,root.right,l1)
l2=self.find_depth(root.left,root.right,l2)
return max(l1,l2)