Created
February 24, 2026 20:28
-
-
Save tatsuyax25/1ac8c9ba8bcf8a0948dfc9ca962f20bf to your computer and use it in GitHub Desktop.
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
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
| /** | |
| * Definition for a binary tree node. | |
| * function TreeNode(val, left, right) { | |
| * this.val = (val===undefined ? 0 : val) | |
| * this.left = (left===undefined ? null : left) | |
| * this.right = (right===undefined ? null : right) | |
| * } | |
| */ | |
| /** | |
| * @param {TreeNode} root | |
| * @return {number} | |
| */ | |
| var sumRootToLeaf = function(root) { | |
| // DFS helper: carries the current binary value down the tree | |
| function dfs(node, currentValue) { | |
| if (!node) { | |
| // Null nodes contribute nothing | |
| return 0; | |
| } | |
| // Build the new binary number by shifting left and adding the current bit | |
| const nextValue = (currentValue << 1) + node.val; | |
| // If this is a leaf, we've completed a full root-to-leaf binary number | |
| if (!node.left && !node.right) { | |
| return nextValue; | |
| } | |
| // Otherwise, explore both children and sum their contributions | |
| return dfs(node.left, nextValue) + dfs(node.right, nextValue); | |
| } | |
| // Start DFS with initial value 0 | |
| return dfs(root, 0); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment