简繁EN

LeetCodeNo. 030

【LeetCode with Python】 104. Maximum Depth of Binary Tree

目錄

題目

原題頁面:https://leetcode.com/problems/maximum-depth-of-binary-tree/
題目型別:Tree, Depth-first Search
難度評價:Easy
類似題目:(E) Balanced Binary Tree, (E) Minimum Depth of Binary Tree

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.


分析

計算二叉樹的最大深度,正規的遞歸回溯解法。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:

def recurMaxDepth(self, root, depth):
if None == root:
return 0
elif None == root.left and None == root.right:
return 1

left_depth = (self.recurMaxDepth(root.left, depth) if None != root.left else 0)
right_depth = (self.recurMaxDepth(root.right, depth) if None != root.right else 0)

# warn: a node just have a child, a node have two child, their height calculation method are different.
if left_depth > 0 and right_depth > 0:
return max(left_depth, right_depth) + 1;
elif left_depth > 0:
return left_depth + 1
else: # right_depth > 0, or (left_depth == 0 and right_depth == 0)
return right_depth + 1

# @param root, a tree node
# @return an integer
def maxDepth(self, root):
return self.recurMaxDepth(root, 0)

本文地址:https://xnerv.wang/zh-tw/leetcode-maximum-depth-of-binary-tree/