LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python

来源:互联网 发布:百度网盘mac版怎么安装 编辑:程序博客网 时间:2024/05/16 09:17

题目:

给定一个二叉树,返回这个二叉树的最大深度

解题思路:

使用递归,保存所有叶子节点的深度。选择这些深度中的最大值,则为该二叉树的最大深度。

代码(Python):

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        List = []        if root==None:            return 0        def readTree(root,count):            if root.left==None and root.right==None:                count = count+1                List.append(count)                return            elif root.left==None and root.right!=None:                count = count+1                readTree(root.right,count)            elif root.left!=None and root.right==None:                count = count+1                readTree(root.left,count)            else:                readTree(root.left,count+1)                readTree(root.right,count+1)                readTree(root,0)        print List        return max(List)

阅读全文
0 0
原创粉丝点击