当前位置:网站首页>Sum of binary numbers from root to leaf
Sum of binary numbers from root to leaf
2022-07-27 04:08:00 【Sharp blade CC】
1022. Sum of binary numbers from root to leaf
The difficulty is simple 212
Give me a binary tree , The value of each node on it is 0 or 1 . Each path from root to leaf represents a binary number starting from the most significant bit .
- for example , If the path is
0 -> 1 -> 1 -> 0 -> 1, Then it represents a binary number01101, That is to say13.
For every leaf on the tree , We all have to find the number represented by the path from the root to the leaf .
Returns the sum of these numbers . The question data guarantees that the answer is 32 position Integers .
Example 1:

Input :root = [1,0,1,0,1,0,1]
Output :22
explain :(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Example 2:
Input :root = [0]
Output :0
Tips :
- The number of nodes in the tree is
[1, 1000]Within the scope of Node.valOnly for0or1
Ideas : Recursive postorder traversal
You need to traverse the binary tree , The first thing to think about is recursion , Break big problems into small ones , Let the left and right subtrees complete the task respectively , Recursion in turn , Until I met nullptr.
- Because we need to count the total , So it defines a Global variables sum , And considering that recursion to the left and right subtrees also needs to pass the sum of the values of the current path , therefore Create a new sub function to complete recursion , Set the parameter to root and val,val Represents the sum of all paths before encountering the current node .
- Then continue the post order traversal :
- If the current node Is a leaf node , Will val The value is assigned to sum, And back to .
- If the current node Is a non leaf node , Then continue to recurse to the left and right subtrees .
/** * 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 sum = 0;
int _sumRootToLeaf(TreeNode* root, int val)
{
if(root == nullptr)
return 0;
val = root->val + (val << 1);
_sumRootToLeaf(root->left, val);
_sumRootToLeaf(root->right, val);
// If it's a leaf node , Then let sum Add the sum of this path
if(root->left == nullptr && root->right == nullptr)
sum += val;
return sum;
}
int sumRootToLeaf(TreeNode* root) {
return _sumRootToLeaf(root, 0);
}
};
Complexity
- Time complexity :O(N),N Is the number of binary tree nodes .
- Spatial complexity :O(N), Stack space used by recursion .
边栏推荐
- 【MySQL系列】MySQL索引事务
- JMeter interface test (login, registration)
- C # using sqlsugar updatable system to report invalid numbers, how to solve it? Ask for guidance!
- Restful Fast Request 2022.2.2发布,支持批量导出文档
- 基于风能转换系统的非线性优化跟踪控制(Matlab代码实现)
- C语言入门实战(12):求自然常数e的值
- Share the current life -- a six week internship experience of a high school graduate in CCTV
- DataX cannot connect to the corresponding database (yes under windows, but failed under Linux)
- MySQL: understand the basic knowledge of MySQL and computer
- Case when in MySQL returns multiple field processing schemes
猜你喜欢
随机推荐
注释有点好玩哦
电商系统结合商品秒杀活动,VR全景不断带来收益
Alibaba cloud server domain name and port web page cannot access the problem record
A. YES or YES?
[Yugong series] July 2022 go teaching course 018 switch of branch structure
222. Number of nodes of complete binary tree
PSINS工具箱中轨迹生成工具详细解析
Greenplum [deployment 08] database small version upgrade process and problem handling error: open-source-greenplum-db-6 conflicts with
Day 28 of leetcode
JVM原理简介
Summer meal | rich people are different from what you think (day 5) + power system power flow simulation (documents and matlab code)
flinkSQLclient创建的job,flink重启就没了,有什么办法吗?
Redis (IX) - redis distributed lock
使用redis c库,异步内存泄露的问题
LeetCode 第二十八天
【obs】动态码率:码率估算
[Android synopsis] kotlin multithreaded programming (I)
flink cdc 到MySQL8没问题,到MySQL5读有问题,怎么办?
"Gonna be right" digital collection is now on sale! Feel the spiritual resonance of artists
There is no problem reading from flick CDC to mysql8 and mysql5. What should I do?









