【Leetcode】【Python】二叉树(一) 最大深度和DFS

1.求二叉树的最大深度
题目:给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节 点数。

二叉树的最大深度为左右子树的最大深度+1
首先使用递归方法求解。
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
    	return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 #调用自身
在使用递归的时候要注意三点:
1.递归结束的条件是什么
2.什么时候调用自身
3.如何调用自身

本题还可以使用迭代(栈)解决问题

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
    
    stack = [(1, root)]
    depth = 0
    while stack:
    	cur_depth, root = stack.pop()
    	depth = max(cur_depth, depth)
    	if root.right:
    		stack.append((cur_depth+1, root.right))
    	if root.left:
    		stack.append((cur_depth+1, root.left))
		
		return depth
因为是先序遍历,所以右孩子先入栈,然后再是左孩子。
在迭代的过程中不断更新depth
最后就得到二叉树的最大深度
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值