程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] leetcode submission example

編輯:Python

【 Reference resources :508. The most frequent sub tree elements and - Power button (LeetCode)】

Write variables and functions like classes

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.cnt=Counter()
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
self.dfs(root)
maxNum=max(self.cnt.values())
res=[k for k,v in self.cnt.items() if v==maxNum ]
return res
def dfs(self,root):
if root is None:return 0
left=self.dfs(root.left)
right=self.dfs(root.right)
he= root.val + left + right
self.cnt[he]+=1
return he

Write the required function inside the function

class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
cnt = Counter()
def dfs(node: TreeNode) -> int:
if node is None:
return 0
sum = node.val + dfs(node.left) + dfs(node.right)
cnt[sum] += 1
return sum
dfs(root) # Call below function 
maxCnt = max(cnt.values())
return [s for s, c in cnt.items() if c == maxCnt]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved