Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Sum of Left Leaves

Easy · Trees · Asked at Amazon, Adobe, TCS, Infosys, Wipro

A left leaf is a node with no children that is the left child of its parent. Print the sum of the values of all left leaves, or 0 if there are none.

Input

First line: k. Second line: k values — the tree in level order, -1 means no node.

Output

The sum of all left leaves.

Constraints

Traverse the tree; at each node, look at its left child — if that child has no children of its own, add its value.

Example 1

Input

7
3 9 20 -1 -1 15 7

Output

24

Example 2

Input

1
1

Output

0

Hints

  1. A node cannot tell by itself that it is a left child — its parent can.
  2. At every node, check its left child: is it a leaf?

Approach

Visit every node (an explicit stack avoids deep recursion). If the node has a left child and that child has neither a left nor a right child, add the child's value. Right leaves and the root itself never count.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
    if (a.empty() || a[0] == -1) return nullptr;
    Node *root = new Node(a[0]);
    queue<Node *> q;
    q.push(root);
    size_t i = 1;
    while (!q.empty() && i < a.size()) {
        Node *cur = q.front();
        q.pop();
        if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
        i++;
        if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
        i++;
    }
    return root;
}

vector<long long> readTree() {
    int k;
    cin >> k;
    vector<long long> a(k);
    for (auto &x : a) cin >> x;
    return a;
}

int main() {
    Node *root = build(readTree());
    long long sum = 0;
    vector<Node *> st = {root};
    while (!st.empty()) {
        Node *n = st.back();
        st.pop_back();
        if (n->left && !n->left->left && !n->left->right) sum += n->left->val;
        if (n->left) st.push_back(n->left);
        if (n->right) st.push_back(n->right);
    }
    cout << sum << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

class Node:
    __slots__ = ("val", "left", "right")

    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build(a):
    """Level order with -1 for a missing child."""
    if not a or a[0] == -1:
        return None
    root = Node(a[0])
    q = deque([root])
    i = 1
    while q and i < len(a):
        cur = q.popleft()
        if i < len(a) and a[i] != -1:
            cur.left = Node(a[i])
            q.append(cur.left)
        i += 1
        if i < len(a) and a[i] != -1:
            cur.right = Node(a[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
total = 0
stack = [root]
while stack:
    node = stack.pop()
    if node.left and not node.left.left and not node.left.right:
        total += node.left.val
    if node.left:
        stack.append(node.left)
    if node.right:
        stack.append(node.right)
print(total)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    // level order with -1 for a missing child
    static Node build(long[] a) {
        if (a.length == 0 || a[0] == -1) return null;
        Node root = new Node(a[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < a.length) {
            Node cur = q.poll();
            if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
            i++;
            if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
            i++;
        }
        return root;
    }

    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    static long next() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static long[] readTree() throws IOException {
        int k = (int) next();
        long[] a = new long[k];
        for (int i = 0; i < k; i++) a[i] = next();
        return a;
    }

    public static void main(String[] args) throws IOException {
        Node root = build(readTree());
        long sum = 0;
        ArrayDeque<Node> st = new ArrayDeque<>();
        st.push(root);
        while (!st.isEmpty()) {
            Node n = st.pop();
            if (n.left != null && n.left.left == null && n.left.right == null) sum += n.left.val;
            if (n.left != null) st.push(n.left);
            if (n.right != null) st.push(n.right);
        }
        System.out.println(sum);
    }
}

Solve Sum of Left Leaves online · All practice problems