Breadth First Search Algorithm to Compute the Sum of the Deepest Nodes


Given a binary tree root, find the sum of the deepest node values.

Constraints
n ≤ 100,000 where n is the number of nodes in root

sum-of-deepest-nodes-binary-tree Breadth First Search Algorithm to Compute the Sum of the Deepest Nodes algorithms BFS c / c++ python

Hint:
You need to get the sum of all the nodes at the last level of the tree. How do you traverse level by level?

Compute the Sum of Deepest Nodes of Binary Tree using BFS Algorithm

Using BFS (Breadth First Search Algorithm), we’ll be able to perform level-by-level traversal. Then for each level as we can expand the nodes in the same level, we compute the sum, and return the last sum when we finish BFS.

C++ BFS Algorithm implementation to compute the sum of the deepest nodes of a binary tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * class Tree {
 *     public:
 *         int val;
 *         Tree *left;
 *         Tree *right;
 * };
 */
int computeLevelOfDeepstNodes(Tree* root) {
    if (!root) {
        return 0;
    }
    int sum = 0;
    queue<Tree*> q;
    q.push(root);
    while (!q.empty()) {
        auto sz = q.size();
        sum = 0;
        for (int i = 0; i < sz; ++ i) {
            auto p = q.front();
            q.pop();
            if (p->left) q.push(p->left);
            if (p->right) q.push(p->right);
            sum += p->val;
        }
    }
    return sum;
}
/**
 * class Tree {
 *     public:
 *         int val;
 *         Tree *left;
 *         Tree *right;
 * };
 */
int computeLevelOfDeepstNodes(Tree* root) {
    if (!root) {
        return 0;
    }
    int sum = 0;
    queue<Tree*> q;
    q.push(root);
    while (!q.empty()) {
        auto sz = q.size();
        sum = 0;
        for (int i = 0; i < sz; ++ i) {
            auto p = q.front();
            q.pop();
            if (p->left) q.push(p->left);
            if (p->right) q.push(p->right);
            sum += p->val;
        }
    }
    return sum;
}

Python code of BFS based on the deque.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self, root):
        if root is None:
            return 0
        q = deque([root])
        lastSum = 0
        while len(q) > 0:
            sz = len(q)
            lastSum = 0
            for _ in range(sz):
                x = q.popleft()
                lastSum += x.val
                if x.left:
                    q.append(x.left)
                if x.right:
                    q.append(x.right)
        return lastSum
# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self, root):
        if root is None:
            return 0
        q = deque([root])
        lastSum = 0
        while len(q) > 0:
            sz = len(q)
            lastSum = 0
            for _ in range(sz):
                x = q.popleft()
                lastSum += x.val
                if x.left:
                    q.append(x.left)
                if x.right:
                    q.append(x.right)
        return lastSum

Time complexity is O(N) and space complexity is also O(N).

See posts of computing the sum of the deepest leaves for a given binary tree:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
557 words
Last Post: Two Pointer Algorithm to Count Triangle Triplets in an Array
Next Post: Teaching Kids Programming - Find the Single Number in Array

The Permanent URL is: Breadth First Search Algorithm to Compute the Sum of the Deepest Nodes

Leave a Reply