Leetcode 1022. Sum of Root To Leaf Binary Numbers
Given a binary tree containing 0s and 1s, each root-to-leaf path represents a binary number starting with the root. For example, if the path is 0 -> 1 -> 1 -> 0, then the binary number is 0110, which is 6 in decimal. Return the sum of these numbers computed for all such paths in the tree.
int val
for the value (0 or 1), and pointers TreeNode* left
and TreeNode* right
for its children.#include <iostream>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
return dfs(root, 0);
}
private:
int dfs(TreeNode* node, int currentSum) {
if (!node) return 0;
currentSum = (currentSum << 1) | node->val;
// If it's a leaf node, return the current accumulated sum
if (!node->left && !node->right) {
return currentSum;
}
// Otherwise, continue the DFS on both subtrees
return dfs(node->left, currentSum) + dfs(node->right, currentSum);
}
};
currentSum << 1
) and adding the node’s value (using binary OR | node->val
).left
and right
are nullptr
), we add the accumulated binary sum to the total sum.With the above approach, we can efficiently compute the sum of all root-to-leaf binary numbers in the given binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?