You are given the root of a binary tree where each node has a 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.
The test cases are generated so that the answer fits in a 32-bits integer.
The number of nodes in the tree is in the range [1, 1000].
Node.val is 0 or 1.
Solutions
Solution 1: Recursion
Thinking
Listing every root-to-leaf path and converting the bits is fine for \(n\le 1000\), but the paths need extra storage. Walking downward, the path value updates as \(t\leftarrow 2t+\textit{val}\) and is complete at a leaf.
A null node contributes \(0\). A node with no children is a leaf and returns the current \(t\); otherwise both subtrees receive the same \(t\) and we add the results.
DFS carries the path value and visits each node once.
We design a recursive function \(\text{dfs}(root, t)\), which takes two parameters: the current node \(root\) and the binary number \(t\) corresponding to the parent node of the current node. The return value of the function is the sum of binary numbers represented by paths from the current node to leaf nodes. The answer is \(\textrm{dfs}(root, 0)\).
The logic of the recursive function is as follows:
If the current node \(root\) is null, return \(0\); otherwise, calculate the binary number \(t\) corresponding to the current node, i.e., \(t = t \ll 1 | root.val\).
If the current node is a leaf node, return \(t\); otherwise, return the sum of \(\textrm{dfs}(root.left, t)\) and \(\textrm{dfs}(root.right, t)\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary tree. Each node is visited once; the recursion stack requires \(O(n)\) space.
1 2 3 4 5 6 7 8 91011121314151617
# 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 = rightclassSolution:defsumRootToLeaf(self,root:Optional[TreeNode])->int:defdfs(root:Optional[TreeNode],x:int)->int:ifrootisNone:return0x=x<<1|root.valifroot.left==root.right:returnxreturndfs(root.left,x)+dfs(root.right,x)returndfs(root,0)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsumRootToLeaf(root*TreeNode)int{vardfsfunc(*TreeNode,int)intdfs=func(root*TreeNode,xint)int{ifroot==nil{return0}x=x<<1|root.Valifroot.Left==root.Right{returnx}returndfs(root.Left,x)+dfs(root.Right,x)}returndfs(root,0)}