[英]Need help understanding Python syntax to write recursion when solving max binary tree depth
問題在於使用遞歸求解二叉樹的最大深度。 最初來自leetcode https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/
我試圖通過一個真實的例子來理解代碼。 root = 3,左子= 9,右子= null。 應該返回2。
具體來說,我不太了解left_height如何獲得1的int值。我知道right_height為None,因此為0。
有人可以真正地講解示例,真是太好了。 我很了解算法。 我對處理python對象不是很熟悉。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
左節點沒有左或右,因此它將返回max(0,0)+1
或1
該調用將樹返回到根,以返回max(1,0)+1
,最終結果為2
我點擊了鏈接,所以這些數字無關緊要
3
/ \
9 20
/ \
15 7
是相同的
.
/ \
. .
/ \
. .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.