Nest Interview Question: Sum of root to leaf nodes in ... | Glassdoor

Interview Question

Software Engineer Interview

Sum of root to leaf nodes in a tree that equals to given

  input value.
Answer

Interview Answer

2 Answers

0

Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found.

Kenneth Ayers on Mar 19, 2017
0

void findSum(treeNode *root, int remainingSum, bool *found) {
    if (!root) {
        return;
    }
    if (*found) {
        return;
    }

    if (!root->left && !root->right && (root->val == remainingSum)) {
        *found = true;
    }

    if (root->val val;
        findSum(root->left, remainingSum, found);
        findSum(root->right, remainingSum, found);
    }
}

recursive solution on Oct 21, 2017

Add Answers or Comments

To comment on this, Sign In or Sign Up.