ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-09-09 06:00:20  阅读:283  来源: 互联网

标签:Binary Leaf helper 1022 res sum root Sum


Given a binary tree, each node has 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.

Example 1:

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

  1. The number of nodes in the tree is between 1 and 1000.
  2. node.val is 0 or 1.
  3. The answer will not exceed 2^31 - 1.

从根到叶的二进制数之和。题意是给一个二叉树,请你返回每条从根节点到叶子节点的路径和。由于路径上的点只有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 题目总结

标签:Binary,Leaf,helper,1022,res,sum,root,Sum
来源: https://www.cnblogs.com/cnoodle/p/13636767.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有