刷题篇--二叉树的最大深度

二叉树的最大深度

该题是leetcode 104,是一道简单的经典题。本文用两种方法去得到二叉树的最大深度。

1.递归

本题递归方法比较简单,也容易理解。涉及树的问题,很多都可以使用递归。

def maxDepth(root):
	if root is None: return 0    #递归都要有终止条件
	ldepth = maxDepth(root.left)
	rdepth = maxDepth(root.right)
	return max(ldepth, rdepth) + 1
2.非递归

非递归方法我们可以使用树的深度遍历,得出每条路径,最长的路径就是树的深度。

def maxDepth(root):
	if root is None: return 0
	res = []
	stack= [(root, [root.val])]

	while stack:
		node, path = stack.pop()
		if node.left is None and node.right is None:
			res.append(path)
		if node.left:
			stack.append((node.left, path+[node.left.val]))
		if node.right:
			stack.append((node.right, path+[node.right.val]))
		
		length = [len(x) for x in res]
	return max(length)			

树的广度遍历、深度遍历应该达到不思考直接写出来的程度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值