Print all Nodes in a Binary Tree having k leaves

Last Updated : 28 May, 2026

Given the root of a binary tree and an integer k (where k >= 1), find all nodes whose subtree contains exactly k leaf nodes.

  • Return the node values in the order they appear in postorder traversal.
  • If no such node exists, return [-1].

Examples : 

Input: root[] = [0, 1, 2], k = 1

2056958146

Output: [-1]
Explanation: There is no node in this tree which has one leaf in the sub tree below it.

Input: root[] = [0, 1, 2, N, N, 4, N, 5, 9], k = 2

2056958144

Output: [4, 2]

2056958145

Explanation: Nodes with data 2 and 4, have 2 leaves (5, 9) in the subtree below it.

Try It Yourself
redirect icon

[Naive Approach] Recount Leaves for Every Node - O(n^2) Time O(h) Space

The idea is to traverse every node of the binary tree and count the number of leaf nodes in its subtree. For each node, if the subtree contains exactly k leaf nodes, store that node in the result. A postorder traversal is used so that left and right subtrees are processed before the current node.

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

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Function to count leaf nodes in subtree
int countLeafNodes(Node *root)
{

    if (root == nullptr)
    {
        return 0;
    }

    // Leaf node
    if (root->left == nullptr && root->right == nullptr)
    {
        return 1;
    }

    return countLeafNodes(root->left) + countLeafNodes(root->right);
}

// Postorder traversal
void postorder(Node *root, int k, vector<int> &res)
{

    if (root == nullptr)
    {
        return;
    }

    postorder(root->left, k, res);
    postorder(root->right, k, res);

    int leaves = countLeafNodes(root);

    // Ignore leaf nodes themselves
    if (root->left != nullptr || root->right != nullptr)
    {

        // Store node if subtree has k leaves
        if (leaves == k)
        {
            res.push_back(root->data);
        }
    }
}

vector<int> kLeafNodes(Node *root, int k)
{

    vector<int> res;

    postorder(root, k, res);

    if (res.empty())
    {
        return {-1};
    }

    return res;
}

// Driver Code
int main()
{

    // Creating tree
    Node *root = new Node(0);

    root->left = new Node(1);
    root->right = new Node(2);

    root->right->left = new Node(4);

    root->right->left->left = new Node(5);
    root->right->left->right = new Node(9);

    int k = 2;

    vector<int> res = kLeafNodes(root, k);

    cout << "[";

    for (int i = 0; i < res.size(); i++)
    {

        cout << res[i];

        if (i != res.size() - 1)
        {
            cout << ", ";
        }
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;

    Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

public class GfG {

    // Function to count leaf nodes in subtree
    static int countLeafNodes(Node root)
    {

        if (root == null) {
            return 0;
        }

        // Leaf node
        if (root.left == null && root.right == null) {
            return 1;
        }

        return countLeafNodes(root.left)
            + countLeafNodes(root.right);
    }

    // Postorder traversal
    static void postorder(Node root, int k,
                          ArrayList<Integer> res)
    {

        if (root == null) {
            return;
        }

        postorder(root.left, k, res);
        postorder(root.right, k, res);

        int leaves = countLeafNodes(root);

        // Ignore leaf nodes themselves
        if (root.left != null || root.right != null) {

            // Store node if subtree has k leaves
            if (leaves == k) {
                res.add(root.data);
            }
        }
    }

    static ArrayList<Integer> kLeafNodes(Node root, int k)
    {

        ArrayList<Integer> res = new ArrayList<>();

        postorder(root, k, res);

        if (res.isEmpty()) {
            res.add(-1);
        }

        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {

        // Creating tree
        Node root = new Node(0);

        root.left = new Node(1);
        root.right = new Node(2);

        root.right.left = new Node(4);

        root.right.left.left = new Node(5);
        root.right.left.right = new Node(9);

        int k = 2;

        ArrayList<Integer> res = kLeafNodes(root, k);

        System.out.print("[");

        for (int i = 0; i < res.size(); i++) {

            System.out.print(res.get(i));

            if (i != res.size() - 1) {
                System.out.print(", ");
            }
        }

        System.out.print("]");
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to count leaf nodes in subtree
def countLeafNodes(root):

    if root is None:
        return 0

    # Leaf node
    if root.left is None and root.right is None:
        return 1

    return countLeafNodes(root.left) + countLeafNodes(root.right)

# Postorder traversal
def postorder(root, k, res):

    if root is None:
        return

    postorder(root.left, k, res)
    postorder(root.right, k, res)

    leaves = countLeafNodes(root)

    # Ignore leaf nodes themselves
    if root.left is not None or root.right is not None:

        # Store node if subtree has k leaves
        if leaves == k:
            res.append(root.data)

def kLeafNodes(root, k):

    res = []

    postorder(root, k, res)

    if not res:
        return [-1]

    return res

# Driver Code
if __name__ == '__main__':

    # Creating tree
    root = Node(0)

    root.left = Node(1)
    root.right = Node(2)

    root.right.left = Node(4)

    root.right.left.left = Node(5)
    root.right.left.right = Node(9)

    k = 2

    res = kLeafNodes(root, k)

    print('[', end='')

    for i in range(len(res)):
        print(res[i], end='')

        if i!= len(res) - 1:
            print(', ', end='')

    print(']')
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to count leaf nodes in subtree
    public static int countLeafNodes(Node root)
    {

        if (root == null) {
            return 0;
        }

        // Leaf node
        if (root.left == null && root.right == null) {
            return 1;
        }

        return countLeafNodes(root.left)
            + countLeafNodes(root.right);
    }

    // Postorder traversal
    public static void postorder(Node root, int k,
                                 List<int> res)
    {

        if (root == null) {
            return;
        }

        postorder(root.left, k, res);
        postorder(root.right, k, res);

        int leaves = countLeafNodes(root);

        // Ignore leaf nodes themselves
        if (root.left != null || root.right != null) {

            // Store node if subtree has k leaves
            if (leaves == k) {
                res.Add(root.data);
            }
        }
    }

    public static List<int> kLeafNodes(Node root, int k)
    {

        List<int> res = new List<int>();

        postorder(root, k, res);

        if (res.Count == 0) {
            res.Add(-1);
        }

        return res;
    }

    // Driver Code
    public static void Main()
    {

        // Creating tree
        Node root = new Node(0);

        root.left = new Node(1);
        root.right = new Node(2);

        root.right.left = new Node(4);

        root.right.left.left = new Node(5);
        root.right.left.right = new Node(9);

        int k = 2;

        List<int> res = kLeafNodes(root, k);

        Console.Write("[");

        for (int i = 0; i < res.Count; i++) {

            Console.Write(res[i]);

            if (i != res.Count - 1) {
                Console.Write(", ");
            }
        }

        Console.Write("]");
    }
}
JavaScript
class Node {
  constructor(val) {
    this.data = val;
    this.left = null;
    this.right = null;
  }
}

// Function to count leaf nodes in subtree
function countLeafNodes(root) {

  if (root === null) {
    return 0;
  }

  // Leaf node
  if (root.left === null && root.right === null) {
    return 1;
  }

  return countLeafNodes(root.left) + countLeafNodes(root.right);
}

// Postorder traversal
function postorder(root, k, res) {

  if (root === null) {
    return;
  }

  postorder(root.left, k, res);
  postorder(root.right, k, res);

  let leaves = countLeafNodes(root);

  // Ignore leaf nodes themselves
  if (root.left!== null || root.right!== null) {

    // Store node if subtree has k leaves
    if (leaves === k) {
      res.push(root.data);
    }
  }
}

function kLeafNodes(root, k) {

  let res = [];

  postorder(root, k, res);

  if (res.length === 0) {
    return [-1];
  }

  return res;
}

// Driver Code
// Creating tree
let root = new Node(0);

root.left = new Node(1);
root.right = new Node(2);

root.right.left = new Node(4);

root.right.left.left = new Node(5);
root.right.left.right = new Node(9);

let k = 2;

let res = kLeafNodes(root, k);

console.log('[');

for (let i = 0; i < res.length; i++) {
  process.stdout.write(res[i].toString());

  if (i!== res.length - 1) {
    process.stdout.write(', ');
  }
}

console.log(']');

Output
[4, 2]

Time Complexity: O(n^2), For every node, we may traverse its entire subtree again.
Auxiliary Space: O(h), where h is the height of the tree.

[Expected Approach] Single DFS Leaf Counting - O(n) Time O(h) Space

The idea is to use a single DFS traversal to count the number of leaf nodes in every subtree. For each node, recursively count the leaf nodes in its left and right subtrees and add them to get the total number of leaves below that node. If the total count becomes equal to k, store that node in the result. Since each node is processed only once, this approach avoids repeated subtree traversals.

Working of Approach:

  • Traverse the binary tree using postorder traversal.
  • For every node, recursively count the number of leaf nodes in its subtree.
  • If the current node is not a leaf node and its subtree contains exactly k leaf nodes, store it in the result.
  • Continue this process for all nodes in the tree.
  • If no such node exists, return [-1].
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Returns the number of leaf nodes in the subtree rooted at 'root'
int countLeaves(Node *root, int k, vector<int> &res)
{

    if (root == nullptr)
    {
        return 0;
    }

    // Leaf node
    if (root->left == nullptr && root->right == nullptr)
    {
        return 1;
    }

    int leftLeaves = countLeaves(root->left, k, res);
    int rightLeaves = countLeaves(root->right, k, res);

    int totalLeaves = leftLeaves + rightLeaves;

    // Store node if its subtree contains exactly k leaves
    if (totalLeaves == k)
    {
        res.push_back(root->data);
    }

    return totalLeaves;
}

vector<int> kLeafNodes(Node *root, int k)
{

    vector<int> res;

    countLeaves(root, k, res);

    if (res.empty())
    {
        return {-1};
    }

    return res;
}

// Driver Code
int main()
{

    // Creating tree
    Node *root = new Node(0);

    root->left = new Node(1);
    root->right = new Node(2);

    root->right->left = new Node(4);

    root->right->left->left = new Node(5);
    root->right->left->right = new Node(9);

    int k = 2;

    vector<int> res = kLeafNodes(root, k);

    cout << "[";

    for (int i = 0; i < res.size(); i++)
    {

        cout << res[i];

        if (i != res.size() - 1)
        {
            cout << ", ";
        }
    }

    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;

    Node(int val)
    {
        data = val;
        left = right = null;
    }
}

public class GfG {
    // Returns the number of leaf nodes in the subtree
    // rooted at 'root'
    static int countLeaves(Node root, int k,
                           ArrayList<Integer> res)
    {
        if (root == null)
            return 0;

        // Leaf node
        if (root.left == null && root.right == null)
            return 1;

        int leftLeaves = countLeaves(root.left, k, res);
        int rightLeaves = countLeaves(root.right, k, res);

        int totalLeaves = leftLeaves + rightLeaves;

        // Store node if its subtree contains exactly k
        // leaves
        if (totalLeaves == k) {
            res.add(root.data);
        }

        return totalLeaves;
    }

    static ArrayList<Integer> kLeafNodes(Node root, int k)
    {
        ArrayList<Integer> res = new ArrayList<>();

        countLeaves(root, k, res);

        if (res.isEmpty()) {
            res.add(-1);
        }

        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        // Creating tree
        Node root = new Node(0);

        root.left = new Node(1);
        root.right = new Node(2);

        root.right.left = new Node(4);

        root.right.left.left = new Node(5);
        root.right.left.right = new Node(9);

        int k = 2;

        ArrayList<Integer> res = kLeafNodes(root, k);

        System.out.print("[");

        for (int i = 0; i < res.size(); i++) {
            System.out.print(res.get(i));

            if (i != res.size() - 1) {
                System.out.print(", ");
            }
        }

        System.out.print("]");
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Returns the number of leaf nodes in the subtree rooted at 'root'


def countLeaves(root, k, res):
    if root is None:
        return 0

    # Leaf node
    if root.left is None and root.right is None:
        return 1

    leftLeaves = countLeaves(root.left, k, res)
    rightLeaves = countLeaves(root.right, k, res)

    totalLeaves = leftLeaves + rightLeaves

    # Store node if its subtree contains exactly k leaves
    if totalLeaves == k:
        res.append(root.data)

    return totalLeaves


def kLeafNodes(root, k):
    res = []

    countLeaves(root, k, res)

    if not res:
        return [-1]

    return res


# Driver Code
if __name__ == '__main__':
    # Creating tree
    root = Node(0)

    root.left = Node(1)
    root.right = Node(2)

    root.right.left = Node(4)

    root.right.left.left = Node(5)
    root.right.left.right = Node(9)

    k = 2

    res = kLeafNodes(root, k)

    print('[', end='')

    for i in range(len(res)):
        print(res[i], end='')

        if i != len(res) - 1:
            print(', ', end='')

    print(']')
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Returns the number of leaf nodes in the subtree
    // rooted at 'root'
    public int countLeaves(Node root, int k, List<int> res)
    {

        if (root == null) {
            return 0;
        }

        // Leaf node
        if (root.left == null && root.right == null) {
            return 1;
        }

        int leftLeaves = countLeaves(root.left, k, res);

        int rightLeaves = countLeaves(root.right, k, res);

        int totalLeaves = leftLeaves + rightLeaves;

        // Store node if its subtree contains exactly k
        // leaves
        if (totalLeaves == k) {
            res.Add(root.data);
        }

        return totalLeaves;
    }

    public List<int> kLeafNodes(Node root, int k)
    {

        List<int> res = new List<int>();

        countLeaves(root, k, res);

        if (res.Count == 0) {
            return new List<int>{ -1 };
        }

        return res;
    }

    // Driver Code
    static void Main(string[] args)
    {

        // Creating tree
        Node root = new Node(0);

        root.left = new Node(1);
        root.right = new Node(2);

        root.right.left = new Node(4);

        root.right.left.left = new Node(5);
        root.right.left.right = new Node(9);

        int k = 2;

        GfG obj = new GfG();

        List<int> res = obj.kLeafNodes(root, k);

        Console.Write("[");

        for (int i = 0; i < res.Count; i++) {

            Console.Write(res[i]);

            if (i != res.Count - 1) {
                Console.Write(", ");
            }
        }

        Console.Write("]");
    }
}
JavaScript
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Returns the number of leaf nodes in the subtree rooted at
// 'root'
function countLeaves(root, k, res)
{
    if (root === null)
        return 0;

    // Leaf node
    if (root.left === null && root.right === null)
        return 1;

    let leftLeaves = countLeaves(root.left, k, res);
    let rightLeaves = countLeaves(root.right, k, res);

    let totalLeaves = leftLeaves + rightLeaves;

    // Store node if its subtree contains exactly k leaves
    if (totalLeaves === k) {
        res.push(root.data);
    }

    return totalLeaves;
}

function kLeafNodes(root, k)
{
    let res = [];

    countLeaves(root, k, res);

    if (res.length === 0) {
        res.push(-1);
    }

    return res;
}

// Driver Code
// Creating tree
let root = new Node(0);

root.left = new Node(1);
root.right = new Node(2);

root.right.left = new Node(4);

root.right.left.left = new Node(5);
root.right.left.right = new Node(9);

let k = 2;

let res = kLeafNodes(root, k);

console.log("[");

for (let i = 0; i < res.length; i++) {
    process.stdout.write(res[i].toString());

    if (i !== res.length - 1) {
        process.stdout.write(", ");
    }
}

console.log("]");

Output
[4, 2]

Time Complexity: O(n), Every node is visited only once.
Auxiliary Space: O(h), where h is the height of the tree.

Comment