求给定二叉树的最大深度,
深度是指树的根节点到任一叶子节点路径上节点的数量。
最大深度是所有叶子节点的深度的最大值。
(注:叶子节点是指没有子节点的节点。)
数据范围:,树上每个节点的val满足
要求: 空间复杂度 ,时间复杂度
要求: 空间复杂度 ,时间复杂度
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 # @return int整型 # class Solution: def maxDepth(self , root ): # write code here # 递归 终止条件为到达叶子节点 if not root: return 0 left_len = self.maxDepth(root.left) right_len = self.maxDepth(root.right) return 1+max(left_len,right_len)
""" 双队列层序遍历 """ class Solution: def maxDepth(self , root ): # write code here if root is None: return 0 q1 = [root] q2 = [] d = 0 while True: if len(q1) <= 0: break d += 1 while len(q1) > 0: x = q1.pop(0) if x.left is not None: q2.append(x.left) if x.right is not None: q2.append(x.right) if len(q2) <= 0: break d += 1 while len(q2) > 0: x = q2.pop(0) if x.left is not None: q1.append(x.left) if x.right is not None: q1.append(x.right) return d
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 # @return int整型 # class Solution: def maxDepth(self, root): return len(self.level_order(root)) def level_order(self, root): """ 层序遍历,输出层数即可 """ result = [] if not root: return result queue = [root] while queue: size = len(queue) v = [] while size > 0: node = queue.pop(0) v.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) size -= 1 if len(v) > 0: result.append(v) return result不过不得不说递归还是简洁呀,怎么就老是想不到呢
class Solution: def maxDepth(self , root ): # write code here if not root: return 0 layer = [root] #first layer res = 0 while layer: res += 1 newlayer = [] #level traverse for node in layer: if node.left: newlayer.append(node.left) if node.right: newlayer.append(node.right) layer = newlayer return res