二叉树最大深度(Python)
二叉树的最大深度
http://www.nowcoder.com/questionTerminal/8a2b2bf6c19b4f23a9bdb9b233eefa73
递归
逻辑就是,左子树的最大深度 和 右子树的最大深度 比大小,再加上本节点 1 的深度。
啪得一下,很快啊,就写好了。
class Solution:
def maxDepth(self , root ):
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 迭代
思路简单来讲就是,创建一个队列(queue),然后把一层的节点都通过 for 遍历到下一层,如此自然每一次 while 循环就是加一层层数,最后返回 cnt。
class Solution:
def maxDepth(self , root ):
if not root:
return 0
queue, cnt= [root], 0
while queue:
cnt += 1
l = len(queue)
for i in range(l):
q = queue.pop(0)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
return cnt