[LeetCode] 1022. Sum of Root To Leaf Binary Numbers

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 represent 01101 in binary, which is 13.

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 is 0 or 1.

从根到叶的二进制数之和。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个二叉树,请你返回每条从根节点到叶子节点的路径和。由于路径上的点只有 0 或 1,所以需要把结果再 convert 成十进制。

这道题的题目跟129题几乎一样,思路也是几乎一样,唯一不同的地方是这道题需要处理二进制到十进制的问题。之前的十进制,每次进位的时候是乘以 10,这道题乘以 2 即可。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     int res = 0;
 3     
 4     public int sumRootToLeaf(TreeNode root) {
 5         helper(root, 0);
 6         return res;
 7     }
 8     
 9     private void helper(TreeNode root, int sum) {
10         if (root == null) {
11             return;
12         }
13         sum = sum * 2 + root.val;
14         if (root.left == null && root.right == null) {
15             res += sum;
16         }
17         helper(root.left, sum);
18         helper(root.right, sum);
19     }
20 }

 

相关题目

129. Sum Root to Leaf Numbers

1022. Sum of Root To Leaf Binary Numbers

LeetCode 题目总结

posted @ 2020-09-09 05:58  CNoodle  阅读(251)  评论(0编辑  收藏  举报