给出一棵二叉树,其上每个结点的值都是 0
或 1
。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1
,那么它表示二进制数 01101
,也就是 13
。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
返回这些数字之和。题目数据保证答案是一个 32 位 整数。
示例 1:
输入:root = [1,0,1,0,1,0,1] 输出:22 解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
示例 2:
输入:root = [0] 输出:0
示例 3:
输入:root = [1] 输出:1
示例 4:
输入:root = [1,1] 输出:3
提示:
- 树中的结点数介于
1
和1000
之间。 Node.val
为0
或1
。
深度优先搜索 DFS 实现。
# 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: 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)
/**
* 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);
}
}
/**
* 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);
}
};
/**
* 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)
}