Python Code to Build Tree and Get Paths
Build Binary Tree and Get Root-to-Leaf Paths
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_tree(arr):
if not arr:
return None
nodes = [TreeNode(v) for v in arr]
for i in range(len(arr)):
left = 2*i + 1
right = 2*i + 2
if left < len(arr):
nodes[i].left = nodes[left]
if right < len(arr):
nodes[i].right = nodes[right]
return nodes[0]
def root_to_leaf_paths(root):
paths = []
def dfs(node, path):
if not node:
return
path.append(node.val)
if not node.left and not node.right:
paths.append(list(path))
else:
dfs(node.left, path)
dfs(node.right, path)
path.pop()
dfs(root, [])
return paths
# Example
arr = [1,0,1,0,2,3,4]
root = build_tree(arr)
print(root_to_leaf_paths(root))
LeetCode Style Solution: Sum Root to Leaf Binary Numbers
# Definition for a binary tree node.
from typing import Optional
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: Optional[TreeNode]) -> int:
# Minimal check for empty tree
if not root:
return 0
# Just return the root-to-leaf sum using the helper
return self.root_to_leaf_paths(root)
def root_to_leaf_paths(self, root: Optional[TreeNode]) -> int:
paths = []
def dfs(node, path):
if not node:
return
path.append(node.val)
if not node.left and not node.right:
paths.append(list(path))
else:
dfs(node.left, path)
dfs(node.right, path)
path.pop()
dfs(root, [])
decimal = 0
for path in paths:
decimal += int("".join(map(str, path)), 2)
return decimal
root = [1,0,1,0,1,0,1]
def buildTree(arr):
if not arr:
return None
nodes = [TreeNode(v) for v in arr]
for i in range(len(arr)):
left = 2*i + 1
right = 2*i + 2
if left < len(arr):
nodes[i].left = nodes[left]
if right < len(arr):
nodes[i].right = nodes[right]
return nodes[0]
arr = buildTree(root)
sol = Solution()
print(sol.sumRootToLeaf(arr))