Hace ya algunos años, cuando cumplí cuarenta y uno, creía llevar una vida como cualquier hombre decente: trabajo estable, un hogar, una esposa y dos hijos. Con Elena, mi mujer, habíamos compartido más de una década de matrimonio. Al principio, todo parecía un cuento: pasión, complicidad, amor. Pero con el tiempo, como suele pasar, la monotonía se instaló entre nosotros. Vivíamos por inercia, repitiendo días idénticos. Aunque manteníamos relaciones y conversaciones, dentro de mí solo había vacío.
Empecé a sentir que perdía mi esencia. Junto a Elena, ya no me sentía un hombre —fuerte, deseado—, sino una sombra, un mueble sin voluntad. Esta sensación me arrastró a la tristeza. Y entonces, en un momento de debilidad, tropecé. En la oficina, en contabilidad, trabajaba una mujer llamada Juana. Durante meses, me sonreía, bromeaba, buscaba mi mirada. Un día, me atreví a invitarla a cenar. Así empezó todo.
Lo curioso fue que, tras comenzar el romance con Juana, mi relación con Elena pareció revivir. Renació la pasión, pasábamos más tiempo juntos. Pero ya era tarde. Me había enamorado. De verdad. Juana no era solo una amante; se convirtió en mi confidente, mi reflejo, mi escape. Con ella, volví a sentirme hombre. Estábamos en sintonía. Sin embargo, vivir entre dos mundos se volvió insoportable.
Fue mi hijo Cristóbal, de dieciséis años, quien destrozó aquella frágil felic# [1022. Sum of Root To Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers)
[中文文档](/solution/1000-1099/1022.Sum%20of%20Root%20To%20Leaf%20Binary%20Numbers/README.md)
## Description
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 represent01101
in binary, which is13
.
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.
Example 1:
Input: root = [1,0,1,0,1,0,1] Output: 22 Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Example 2:
Input: root = [0] Output: 0
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. Node.val
is0
or1
.
## Solutions
### **Python3**
“`python
# 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(root, t):
if root is None:
return 0
t = (t << 1) | root.val
if root.left is None and root.right is None:
return t
return dfs(root.left, t) + dfs(root.right, t)
return dfs(root, 0)
```
### **Java**
```java
/**
* 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 root, int t) {
if (root == null) {
return 0;
}
t = (t << 1) | root.val;
if (root.left == null && root.right == null) {
return t;
}
return dfs(root.left, t) + dfs(root.right, t);
}
}
```
### **C++**
```cpp
/**
* 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);
}
int dfs(TreeNode* root, int t) {
if (!root) return 0;
t = (t << 1) | root->val;
if (!root->left && !root->right) return t;
return dfs(root->left, t) + dfs(root->right, t);
}
};
“`
### **Go**
“`go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumRootToLeaf(root *TreeNode) int {
var dfs func(root *TreeNode, t int) int
dfs = func(root *TreeNode, t int) int {
if root == nil {
return 0
}
t = (t << 1) | root.Val
if root.Left == nil && root.Right == nil {
return t
}
return dfs(root.Left, t) + dfs(root.Right, t)
}
return dfs(root, 0)
}
```
### **TypeScript**
```ts
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumRootToLeaf(root: TreeNode | null): number {
const dfs = (root: TreeNode | null, num: number) => {
if (root == null) {
return 0;
}
const { val, left, right } = root;
num = (num << 1) | val;
if (left == null && right == null) {
return num;
}
return dfs(left, num) + dfs(right, num);
};
return dfs(root, 0);
}
```
### **Rust**
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option
// pub right: Option
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val1: i32) -> Self {
// TreeNode {
// val: val1,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
fn dfs(root: &Option