Getting everything ready for you…

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

0s

Practice › Trees

Largest Value in Each Level

Medium · Trees · Asked at Amazon, Microsoft, LinkedIn

For every level of the tree, from the root level downwards, print the largest value on that level.

Input

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

Output

The largest value of each level, space-separated.

Constraints

BFS one level at a time (process exactly the queue’s current size per level) and track the maximum of each level.

Example 1

Input

7
1 3 2 5 3 -1 9

Output

1 3 9

Example 2

Input

3
1 2 3

Output

1 3

Hints

  1. Process the tree one level at a time with BFS.
  2. The number of nodes in the queue at the start of a level is the size of that level.

Approach

Level-order traversal: at the start of each level, note the queue size s, pop exactly s nodes while tracking their maximum, and push their children. Record the maximum after each level.

Complexity: O(n) time · O(width) 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());
    queue<Node *> q;
    q.push(root);
    string out;
    while (!q.empty()) {
        long long best = LLONG_MIN;
        for (int s = q.size(); s > 0; s--) {
            Node *n = q.front();
            q.pop();
            best = max(best, n->val);
            if (n->left) q.push(n->left);
            if (n->right) q.push(n->right);
        }
        out += (out.empty() ? "" : " ") + to_string(best);
    }
    cout << out << "\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]])
out = []
level = [root]
while level:
    out.append(max(n.val for n in level))
    level = [c for n in level for c in (n.left, n.right) if c]
print(*out)

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());
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        StringBuilder sb = new StringBuilder();
        while (!q.isEmpty()) {
            long best = Long.MIN_VALUE;
            for (int s = q.size(); s > 0; s--) {
                Node n = q.poll();
                best = Math.max(best, n.val);
                if (n.left != null) q.add(n.left);
                if (n.right != null) q.add(n.right);
            }
            if (sb.length() > 0) sb.append(' ');
            sb.append(best);
        }
        System.out.println(sb);
    }
}

Solve Largest Value in Each Level online · All practice problems