leetcode 104 二叉樹的最大深度

2021-08-27 16:10:12 字數 1301 閱讀 8150

給定乙個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

3 / \

9 20

/ \

15 7

返回它的最大深度 3 。

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution:

defmaxdepth

(self, root):

""" :type root: treenode

:rtype: int

"""defdepth

(p):

#遞迴函式

if p is

none:

return

1else:

return

1 + max(depth(p.left),depth(p.right))

if root is

none:

return

0else:

return max(depth(root.left),depth(root.right))

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution:

defmaxdepth

(self, root):

""" :type root: treenode

:rtype: int

"""if root == none:

return

0return max(self.maxdepth(root.left), self.maxdepth(root.right)) + 1

LeetCode104二叉樹最大深度

給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 返回它的最大深度 3 definition for a binary tree node....

LeetCode 104 二叉樹的最大深度

題目描述 給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回它的最大深度 3 解題思路 此題可以用層次遍歷來解,每層設定乙個count值來...

LeetCode 104 二叉樹的最大深度

給定乙個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明 葉子節點是指沒有子節點的節點。示例 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 返回它的最大深度 3 遞迴唄 definition for a binary tree n...