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.
这题要返回树的最大深度~ 递归解法很简单
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
还有一种非递归解法,采用层序遍历
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None: return 0
depth = 1
queue = [root, None]
while len(queue) > 1:
node = queue.pop(0)
if node is None:
depth += 1
queue.append(None)
continue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth