题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
测试用例:
给定二叉树 [3,9,20,null,null,15,7]
3
/
9 20
/
15 7
# 返回值
>>> 3
致谢:
来源:力扣(LeetCode)
链接:力扣
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
- 执行用时:28 ms, 在所有 Python 提交中击败了83.64%的用户
- 内存消耗:15.5 MB, 在所有 Python 提交中击败了7.69%的用户
- 执行消耗内存为 14476 kb 的范例:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
stack = []
if root is not None:
stack.append((1,root))
deep=0
while stack != []:
c_deepth, root = stack.pop()
if root is not None:
deep = max(c_deepth, deep)
stack.append((c_deepth + 1, root.right))
stack.append((c_deepth + 1, root.left))
return deep
知识点复习:
1 树
# 定义
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
# 创建根节点
root = TreeNode(3)
# 创建叶子节点
left = TreeNode(9)
root.left = left
2 BFS & DFS
爱知识的lz:LeetCode | 一文帮你搞定BFS、DFS算法(python版)zhuanlan.zhihu.com