今天好像也没什么好吐槽的
这段时间事儿也挺多的
不知道怎么说
直接写文章吧!!!
104-二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
思路:
这一题有两种解法,第一种是用层次遍历得到二叉树的最大深度,关于层次遍历,前面我们做了好几道题,读者可参考第102题-二叉树的层次遍历:
https://blog.csdn.net/weixin_36431280/article/details/89415290
前面的题目是用层次遍历得到二叉树每一层的节点值,这一题是求二叉树的最大深度,只需要用个len()方法就很容易得到了,很easy,大家直接看代码吧!
代码如下:
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
"""
# 定义二叉树的最大深度
max_depth = 0
# 该列表用来保存当前遍历的一层的节点
current_nodes = [root]
if root:
max_depth += 1
while current_nodes:
next_nodes = []
for node in current_nodes:
if node.left and node.left.val is not None:
next_nodes.append(node.left)
if node.right and node.right.val is not None:
next_nodes.append(node.right)
if next_nodes:
max_depth += 1
current_nodes = next_nodes
return max_depth
def createBTree(self, data, index=0):
pNode = None
if index < len(data):
pNode = TreeNode(data[index])
pNode.left = self.createBTree(data, 2*index+1)
pNode.right = self.createBTree(data, 2*index+2)
return pNode
if __name__ == "__main__":
data = [3, 9, 20, None, None, 15, 7]
root = Solution().createBTree(data)
max_depth = Solution().maxDepth(root)
print(max_depth)
此种方法的执行效率也是很高,达到了99%
方法二:递归遍历
分别对二叉树root的左子树和右子树进行递归遍历,取左子树和右子树的最大深度+1即为整颗二叉树的最大深度,直接看代码:
代码如下:
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
"""
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) if root else 0
def createBTree(self, data, index=0):
pNode = None
if index < len(data):
pNode = TreeNode(data[index])
pNode.left = self.createBTree(data, 2*index+1)
pNode.right = self.createBTree(data, 2*index+2)
return pNode
if __name__ == "__main__":
data = [3, 9, 20, None, None, 15, 7]
root = Solution().createBTree(data)
max_depth = Solution().maxDepth(root)
print(max_depth)
执行效率也是不错,在75%左右。