
題目決議:
利用遞回的代碼如下:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if root==None: return 0 if self.maxDepth(root.left)>self.maxDepth(root.right): return self.maxDepth(root.left)+1 else: return self.maxDepth(root.right)+1
我的方法在正常情況下是沒問題的,但是要是給出用例太多就會超過時間,因此采用下面這種寫法即可:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if root==None: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right))+1

時間復雜度還是太大了,用時太多,時間復雜度更小的方法之后在補充,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/144603.html
標籤:其他
