/**
* Problem: LeetCode 1022 - Sum of Root To Leaf Binary Numbers
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode node, int current) {
if (node == null) {
return 0;
}
current = (current << 1) | node.val;
// Leaf node reached
if (node.left == null && node.right == null) {
return current;
}
return dfs(node.left, current) + dfs(node.right, current);
}
}
"""
Problem: LeetCode 1022 - Sum of Root To Leaf Binary Numbers
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import Optional
# 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: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode], current: int) -> int:
if not node:
return 0
current = (current << 1) | node.val
if not node.left and not node.right:
return current
return dfs(node.left, current) + dfs(node.right, current)
return dfs(root, 0)
/**
* Problem: LeetCode 1022 - Sum of Root To Leaf Binary Numbers
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
/**
* 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 current) {
if (!node) {
return 0;
}
current = (current << 1) | node->val;
if (!node->left && !node->right) {
return current;
}
return dfs(node->left, current) + dfs(node->right, current);
}
};
/**
* Problem: LeetCode 1022 - Sum of Root To Leaf Binary Numbers
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* 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) {
function dfs(node, current) {
if (!node) {
return 0;
}
current = (current << 1) | node.val;
if (!node.left && !node.right) {
return current;
}
return dfs(node.left, current) + dfs(node.right, current);
}
return dfs(root, 0);
};
TIME COMPLEXITY
O(N)
SPACE COMPLEXITY
O(H)
TOPICS
Bit Manipulation
Breadth-First Search / Depth-First Search
Tree / Binary Tree