LeetCode : 1302 Deepest Leaves Sum | Depth First Search (DFS) Solution with Python
LeetCode Problem : https://leetcode.com/problems/deepest-leaves-sum/description/
# 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): height = 0 result = 0 def deepestLeavesSum(self, root): """ :type root: TreeNode :rtype: int """ self.helper(root,1) return self.result def helper(self, root , depth ) : if root is None : return 0 # Check if it is a Leaf Node and Depth is greater than Heigh # Then update result variable if depth > self.height and root.left is None and root.right is None : self.height = depth self.result = root.val elif depth == self.height: # If nodes are at same depth then , add value to global result. self.result += root.val # During each node traversal , increase depth by 1. left = self.helper(root.left,depth +1 ) right = self.helper(root.right ,depth +1 )
Comments
Post a Comment