1. 程式人生 > >104. Maximum Depth of Binary Tree [easy] (Python)

104. Maximum Depth of Binary Tree [easy] (Python)

題目連結

題目原文

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

題目翻譯

給定一個二叉樹,求其最大深度。
最大深度指的是,從根節點到最遠的葉子節點的最長路徑的節點個數。

思路方法

思路一

深度優先搜尋(DFS),遞迴求解。

程式碼

# Definition for a binary tree node.
# class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return
0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

思路二

廣度優先搜尋(BFS),利用佇列求解。

程式碼

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

class Solution(object)
:
def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 depth = 0 q = [root] while len(q) != 0: depth += 1 for i in range(0, len(q)): if q[0].left: q.append(q[0].left) if q[0].right: q.append(q[0].right) del q[0] return depth