题目
给出一棵二叉树,其上每个结点的值都是 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提示:
树中的节点数在 [1, 1000] 范围内
Node.val 仅为 0 或 1来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
先序遍历,遍历到叶子结点时将从根节点到该叶子结点的二进制数num加到ans中。
num可以通过每次将之前的num左移一位然后和当前val异或与求得。即
注意,要在遍历到叶子结点进行「第一句话」的操作,不能到了null结点再加,那样可能会重复累加。
代码
代码一
/**
* 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 {
int ans = 0;
public int sumRootToLeaf(TreeNode root) {
dfs(root, 0);
return ans;
}
private void dfs(TreeNode root, int num) {
if (root == null) {
return;
}
num = num << 1 | root.val;
if (root.left == null && root.right == null) {
ans += num;
return;
}
dfs(root.left, num);
dfs(root.right, num);
}
}
代码二
下面是官解的dfs带返回值的写法
class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int val) {
if (root == null) {
return 0;
}
val = (val << 1) | root.val;
if (root.left == null && root.right == null) {
return val;
}
return dfs(root.left, val) + dfs(root.right, val);
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/solution/cong-gen-dao-xie-de-er-jin-zhi-shu-zhi-h-eqss/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。