Getting everything ready for you…

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

0s

Practice › Trees

Count Good Nodes in a Binary Tree

Medium · Trees · Asked at Microsoft, Amazon, Google

A node is good if no node on the path from the root to it (including the root, excluding itself) has a value greater than it. Print the number of good nodes. The root is always good.

Input

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

Output

The number of good nodes.

Constraints

DFS carrying the maximum value seen on the path so far. A node is good when its value is at least that maximum.

Example 1

Input

7
3 1 4 3 -1 1 5

Output

4

Example 2

Input

5
3 3 -1 4 2

Output

3

Hints

  1. Whether a node is good depends only on the largest value above it.
  2. Pass that maximum down while traversing.

Approach

DFS with an explicit stack of (node, max value on the path above it); the root starts with a maximum smaller than any value. A node is good if its value ≥ that maximum. Its children inherit max(maximum, node value).

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());
    int good = 0;
    vector<pair<Node *, long long>> st = {{root, LLONG_MIN}};
    while (!st.empty()) {
        auto _b = st.back();
        auto n = _b.first;
        auto mx = _b.second;
        st.pop_back();
        if (n->val >= mx) good++;
        long long m2 = max(mx, n->val);
        if (n->left) st.push_back({n->left, m2});
        if (n->right) st.push_back({n->right, m2});
    }
    cout << good << "\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]])
good = 0
stack = [(root, float("-inf"))]
while stack:
    node, mx = stack.pop()
    if node.val >= mx:
        good += 1
    m2 = max(mx, node.val)
    if node.left:
        stack.append((node.left, m2))
    if node.right:
        stack.append((node.right, m2))
print(good)

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());
        int good = 0;
        ArrayDeque<Object[]> st = new ArrayDeque<>();
        st.push(new Object[] {root, Long.MIN_VALUE});
        while (!st.isEmpty()) {
            Object[] t = st.pop();
            Node n = (Node) t[0];
            long mx = (long) t[1];
            if (n.val >= mx) good++;
            long m2 = Math.max(mx, n.val);
            if (n.left != null) st.push(new Object[] {n.left, m2});
            if (n.right != null) st.push(new Object[] {n.right, m2});
        }
        System.out.println(good);
    }
}

Solve Count Good Nodes in a Binary Tree online · All practice problems