Created
September 8, 2020 12:51
-
-
Save kuntalchandra/e4c09befd607705be63a1f12aaf82805 to your computer and use it in GitHub Desktop.
Sum of Root To Leaf Binary Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the | |
| most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, | |
| which is 13. | |
| For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. | |
| Return the sum of these numbers. | |
| Example 1: | |
| 1 | |
| / \ | |
| 0 1 | |
| / \ / \ | |
| 0 1 0 1 | |
| Input: [1,0,1,0,1,0,1] | |
| Output: 22 | |
| Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 | |
| """ | |
| # 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 sumRootToLeaf(self, root: TreeNode) -> int: | |
| stack = [(root, "")] | |
| res = 0 | |
| while stack: | |
| node, path = stack.pop() | |
| if not node.left and not node.right: | |
| path += str(node.val) | |
| res += int(path, 2) | |
| if node.left: | |
| stack.append((node.left, path + str(node.val))) | |
| if node.right: | |
| stack.append((node.right, path + str(node.val))) | |
| return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment