您的位置:首页 > 编程语言 > Python开发

Python3实现二叉树的最大深度

2019-09-30 14:11 1371 查看

问题提出:

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

说明: 叶子节点是指没有子节点的节点。

解决思路:递归法求解。从根结点向下遍历,每遍历到子节点depth+1。

代码实现( ̄▽ ̄):

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, x):
#     self.val = x
#     self.left = None
#     self.right = None

class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root==None:
return 0
count = self.getDepth(root,0)
return count

def getDepth(self,node,count):
if node!=None:
num1 = self.getDepth(node.left,count+1);
num2 = self.getDepth(node.right,count+1);
num = num1 if num1>num2 else num2
return num
else:
return count

时间和空间消耗:

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息