当前位置: 首页 > 后端技术 > Python

二叉树的最大深度(Python3)

时间:2023-03-26 11:22:20 Python

问题:给定一棵二叉树,找到它的最大深度。二叉树的深度是从根节点到最远叶节点的最长路径上的节点数。解释:叶节点是指没有子节点的节点。求解思路:用递归的方法求解。从根节点向下遍历,每次遍历到子节点深度+1。代码实现( ̄▽ ̄):#定义一个二叉树节点。#classTreeNode:#def__init__(self,x):#self.val=x#self.left=None#self.right=Noneclass解法:defmaxDepth(self,root:TreeNode)->int:ifroot==None:return0count=self.getDepth(root,0)返回计数defgetDepth(self,node,count):ifnode!=None:num1=self.getDepth(node.left,count+1);num2=self.getDepth(node.right,count+1);num=num1ifnum1>num2elsenum2returnnumelse:returncount时空消耗:问题来源:https://leetcode-cn.com/probl...