From 227c930944952681a790bdb6c32502224d9581ef Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Wed, 21 Sep 2022 11:35:59 -0400 Subject: [PATCH] Time: 406 ms (31.53%), Space: 20.7 MB (96.88%) - LeetHub --- .../1302-deepest-leaves-sum.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 1302-deepest-leaves-sum/1302-deepest-leaves-sum.py diff --git a/1302-deepest-leaves-sum/1302-deepest-leaves-sum.py b/1302-deepest-leaves-sum/1302-deepest-leaves-sum.py new file mode 100644 index 0000000..63a1455 --- /dev/null +++ b/1302-deepest-leaves-sum/1302-deepest-leaves-sum.py @@ -0,0 +1,36 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def deepestLeavesSum(self, root): + """ + :type root: TreeNode + :rtype: int + """ + + currentLevel = [root] # Holds all the nodes in the current depth + hasNewLevel = root.left != None or root.right != None # True if root has children, otherwise False + + # Processes all children into a new array + while hasNewLevel: + hasNewLevel = False + newLevel = [] + for node in currentLevel: + if node.left != None: + newLevel.append(node.left) + hasNewLevel = True + if node.right != None: + newLevel.append(node.right) + hasNewLevel = True + currentLevel = newLevel if hasNewLevel else currentLevel + + # Computes the sum of current level nodes + levelSum = 0 + for node in currentLevel: + levelSum += node.val + + return levelSum + \ No newline at end of file