Skip to content

Commit 3b167d1

Browse files
ADD sum of root to leaf binary algorithm
1 parent 41f66e1 commit 3b167d1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Algorithms/sumOfRootToLeafBinary.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int rootToLeaf = 0;
15+
16+
void preorder(TreeNode* curr, int currNumber) {
17+
if(curr == nullptr)
18+
return;
19+
currNumber = (currNumber << 1) | curr->val;
20+
21+
if(curr->left == nullptr && curr->right == nullptr)
22+
rootToLeaf += currNumber;
23+
24+
preorder(curr->left, currNumber);
25+
preorder(curr->right, currNumber);
26+
}
27+
28+
29+
int sumRootToLeaf(TreeNode* root) {
30+
preorder(root, 0);
31+
32+
return rootToLeaf;
33+
}
34+
};

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ Click to expand the 43 *C++ programs*!
159159
- sumNodesEvenGrandparent.cpp
160160
- Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.) If there are no nodes with an even-valued grandparent, return 0.
161161
- Leetcode problem found [here](https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/)
162+
- sumOfRootToLeafBinary.cpp
163+
- 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.
164+
- Leetcode problem found [here](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/)
162165
- toLowerCase.cpp
163166
- Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
164167
- word2num.cpp

0 commit comments

Comments
 (0)