且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

leetcode:Maximum Depth of Binary Tree【Python版】

更新时间:2022-09-03 16:14:03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    # @param root, a tree node
    # @return an integer
    def maxDepth(self, root):
        if root == None:
            return 0
        l,r = 1,1
        if root.left != None:
            = l+self.maxDepth(root.left)
        if root.right != None:
            = r+self.maxDepth(root.right)
        if l>r:
            return l
        else:
            return r

1、在开始的时候经常遇到“NoneType”Error,后来查阅资料才知道使用 root==None 就可以处理这种情况;

2、调用函数的时候不需要传递self值,这个应该是Python自己传递的,如果自己添加上,反而会报错;

3、这道题目说明不是很清晰,系统的输入是{},{0},{0,0,0,0,#,#,0,#,#,#,0},{1,2}等形式,然后后台会自动构建二叉树;


本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/4027775.html,如需转载请自行联系原作者