파비의 매일매일 공부기록

2023.11.03 Today's Challenge 본문

Problem Solving/LeetCode

2023.11.03 Today's Challenge

fabichoi 2023. 11. 3. 23:45

https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/

 

Count Nodes Equal to Average of Subtree - LeetCode

Can you solve this real interview question? Count Nodes Equal to Average of Subtree - Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: * The average of n ele

leetcode.com

DFS로 푸는 문제. 
몇일째 트리문제만 나오는중 ㅋㅋ

class Solution:
    def __init__(self):
        self.msc = 0

    def cal(self, cnode):
        if cnode is None:
            return 0, 0
        
        ls = self.cal(cnode.left)
        rs = self.cal(cnode.right)

        sv = ls[0] + rs[0] + cnode.val
        nn = ls[1] + rs[1] + 1

        if sv // nn == cnode.val:
            self.msc += 1
        
        return sv, nn

    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
        self.cal(root)
        return self.msc
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.11.05 Today's Challenge  (0) 2023.11.05
2023.11.04 Today's Challenge  (0) 2023.11.04
2023.11.02 Today's Challenge  (0) 2023.11.02
2023.11.01 Today's Challenge  (0) 2023.11.01
2023.10.31 Today's Challenge  (0) 2023.10.31
Comments