题目

给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。

例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

返回这些数字之和。题目数据保证答案是一个 32 位 整数。

示例 1: image.png

输入: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异或与求得。即1022. 从根到叶的二进制数之和 - 图2

注意,要在遍历到叶子结点进行「第一句话」的操作,不能到了null结点再加,那样可能会重复累加。

代码

代码一

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. int ans = 0;
  18. public int sumRootToLeaf(TreeNode root) {
  19. dfs(root, 0);
  20. return ans;
  21. }
  22. private void dfs(TreeNode root, int num) {
  23. if (root == null) {
  24. return;
  25. }
  26. num = num << 1 | root.val;
  27. if (root.left == null && root.right == null) {
  28. ans += num;
  29. return;
  30. }
  31. dfs(root.left, num);
  32. dfs(root.right, num);
  33. }
  34. }

代码二

下面是官解的dfs带返回值的写法

  1. class Solution {
  2. public int sumRootToLeaf(TreeNode root) {
  3. return dfs(root, 0);
  4. }
  5. public int dfs(TreeNode root, int val) {
  6. if (root == null) {
  7. return 0;
  8. }
  9. val = (val << 1) | root.val;
  10. if (root.left == null && root.right == null) {
  11. return val;
  12. }
  13. return dfs(root.left, val) + dfs(root.right, val);
  14. }
  15. }
  16. 作者:LeetCode-Solution
  17. 链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/solution/cong-gen-dao-xie-de-er-jin-zhi-shu-zhi-h-eqss/
  18. 来源:力扣(LeetCode
  19. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。