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 answer is guaranteed to fit in a 32-bits integer.

Example:

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

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};

int ans = 0;
int toDecimal(vector<ints)
{
    int decimal = 0;
    int n = s.size();
    for (int i = 0i < ni++)
    {
        if (s[i] == 1)
            decimal += pow(2n - i - 1);
    }
    return decimal;
}
void dfs(TreeNode *rootstring strvector<intpath)
{
    if (root == NULL)
        return;
    path.push_back(root->data);
    if (root->left == NULL && root->right == NULL)
    {
        ans += toDecimal(path);
    }

    dfs(root->leftstrpath);
    dfs(root->rightstrpath);
}
int sumRootToLeaf(TreeNode *root)
{
    string str = "";
    vector<intpath;
    dfs(rootstrpath);
    return ans;
}

int main()
{
    TreeNode *root = new TreeNode(1);
    root->left = new TreeNode(0);
    root->right = new TreeNode(1);
    root->left->left = new TreeNode(0);
    root->left->right = new TreeNode(1);
    root->right->left = new TreeNode(0);
    root->right->right = new TreeNode(1);

    cout << sumRootToLeaf(root);
    return 0;
}


No comments:

Post a Comment