Python | DFS(Preorder Traversal)
Our goal is to iterate each and every node by using any kind of traversal technique (preorder, postorder, inorder). (I have used preorder here), \n\nFor every n
Our goal is to iterate each and every node by using any kind of traversal technique (preorder, postorder, inorder). (I have used preorder here), \n\nFor every node, we calculate the sum of its subtree nodes and keep a variable to store the no. of nodes, \nso that we can calculate average by total sum/ total nodes.\n\nIf our average is equal to value of the root, we increment the count.\n\nVideo explanation: https://youtu.be/y_3TlyzIRbk\n\nCode:\n\n\n```\nclass Solution:\n    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n        \n        \n        def calculate_average(root):\n            if root:\n                self.summ+=root.val\n                self.nodecount+=1\n                calculate_average(root.left)\n                calculate_average(root.right)\n        \n        \n        def calculate_for_each_node(root):\n            if root:\n                self.summ = 0\n                self.nodecount = 0\n                calculate_average(root)\n                if ((self.summ)//(self.nodecount)) == root.val:\n                    self.count+=1 \n                calculate_for_each_node(root.left)\n                calculate_for_each_node(root.right)\n                \n                \n        self.count = 0\n        calculate_for_each_node(root)       \n        return self.count\n\n```
['Recursion', 'Python']