1.若为二叉树:
Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack
Base Case: 当Node为空的时候,返回高度为0
Recursive Rule精确版本 :
传递: 左右孩子
向下索取:下一层的左子树和右子树索取最高深度
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。
Recursive Rule说人话:
谁高取谁,并加一
def maxDepth(self, root):
if not root:
return 0
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
def maxDepth(self, root):
if not root:
return 0
depth=0
queue = collections.deque()
queue.append(root)
while queue:
depth += 1
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
2.N叉树:
二叉树每层比对左右孩子,那么N叉树我们在每一层创建一个临时的List用来保存当前Node的所有子孩子传递上来的高度,取其最大返回
class Solution(object):
def maxDepth(self, root):
if not root: return 0
if not root.children: return 1
height = []
for node in root.children:
height.append(self.maxDepth(node))
return max(height) + 1