题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
又是递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
if root.left or root.right:
return 1+max(self.maxDepth(root.right),self.maxDepth(root.left))
elif not (root.left or root.right):
return 1
对一个节点处理,用一加上两个儿子节点深度的最大值,当遇到None的时候返回0
执行用时 :48 ms, 在所有 Python3 提交中击败了65.51%的用户
内存消耗 :15 MB, 在所有 Python3 提交中击败了5.10%的用户
迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root:
max_depth=1
else:
return 0
stack=[(1,root)]
while stack:
cur_depth,root=stack.pop()
max_depth=max(max_depth,cur_depth)
if root.left:
stack.append((cur_depth+1,root.left))
if root.right:
stack.append((cur_depth+1,root.right))
return max_depth
之前写的时候没有想到能用两个变量来承接,就做不下去,这个是看题解的方法来写的
叫DFS?对这个不是特别了解
执行用时 :68 ms, 在所有 Python3 提交中击败了19.01%的用户
内存消耗 :14.4 MB, 在所有 Python3 提交中击败了29.65%的用户