Find K smallest leaf nodes from a given Binary Tree
Last Updated :
21 Jun, 2021
Given a binary tree and an integer K, the task is to find the K smallest leaf nodes from the given binary tree. The number of leaf nodes will always be at least K.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ \
21 8 19
Output: 6 8 19
Explanation:
There are 4 leaf nodes in the above binary tree
out of which 6, 8, 19 are the smallest three leaf nodes.
Input:
11
/ \
12 3
/ \ / \
41 15 61 1
\
8
Output: 1 8 15
Explanation:
There are 4 leaf nodes in the above binary tree
out of which 1, 8, 15 are the smallest three leaf nodes.
Approach: Follow the steps below to solve the problem:
- Traverse the Binary Tree.
- Check for each node if it contains neither left child nor the right child. If found to be true, then that node is a leaf node. Store all such nodes in an array.
- Sort the array of leaf nodes and print the K smallest leaf values from the array.
Below is the implementation of the above approach:
C++
// C++ program of the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of
// binary tree node
struct Node {
int data;
Node *left, *right;
};
// Function to create new node
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Utility function which calculates
// smallest three nodes of all leaf nodes
void storeLeaf(Node* root, vector<int>& arr)
{
if (!root)
return;
// Check if current root is a leaf node
if (!root->left and !root->right) {
arr.push_back(root->data);
return;
}
// Traverse the left
// and right subtree
storeLeaf(root->left, arr);
storeLeaf(root->right, arr);
}
// Function to find the K smallest
// nodes of the Binary Tree
void KSmallest(Node* root, int k)
{
vector<int> arr;
storeLeaf(root, arr);
// Sorting the Leaf nodes array
sort(arr.begin(), arr.end());
// Loop to print the K smallest
// Leaf nodes of the array
for (int i = 0; i < k; i++) {
if (i < arr.size()) {
cout << arr[i] << " ";
}
else {
break;
}
}
}
// Driver Code
int main()
{
// Construct binary tree
Node* root = newNode(1);
root->left = newNode(2);
root->left->left = newNode(4);
root->left->left->left = newNode(21);
root->left->right = newNode(5);
root->left->right->right = newNode(8);
root->right = newNode(3);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->right->right = newNode(19);
// Function Call
KSmallest(root, 3);
return 0;
}
Java
// Java program of the
// above approach
import java.util.*;
class GFG{
// Structure of
// binary tree node
static class Node
{
int data;
Node left, right;
};
// Function to create new node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Utility function which calculates
// smallest three nodes of all leaf nodes
static Vector<Integer> storeLeaf(Node root,
Vector<Integer> arr)
{
if (root == null)
return arr;
// Check if current root is a leaf node
if (root.left == null &&
root.right == null)
{
arr.add(root.data);
return arr;
}
// Traverse the left
// and right subtree
arr = storeLeaf(root.left, arr);
arr = storeLeaf(root.right, arr);
return arr;
}
// Function to find the K smallest
// nodes of the Binary Tree
static void KSmallest(Node root, int k)
{
Vector<Integer> arr = new Vector<Integer>();
arr = storeLeaf(root, arr);
// Sorting the Leaf nodes array
Collections.sort(arr);
// Loop to print the K smallest
// Leaf nodes of the array
for(int i = 0; i < k; i++)
{
if (i < arr.size())
{
System.out.print(arr.get(i) + " ");
}
else
{
break;
}
}
}
// Driver Code
public static void main(String[] args)
{
// Construct binary tree
Node root = newNode(1);
root.left = newNode(2);
root.left.left = newNode(4);
root.left.left.left = newNode(21);
root.left.right = newNode(5);
root.left.right.right = newNode(8);
root.right = newNode(3);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.right.right = newNode(19);
// Function call
KSmallest(root, 3);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program for the
# above approach
# Binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Utility function which calculates
# smallest three nodes of all leaf nodes
def storeLeaf(root: Node,
arr : list) -> None:
if (not root):
return
# Check if current root
# is a leaf node
if (not root.left and
not root.right):
arr.append(root.data)
return
# Traverse the left
# and right subtree
storeLeaf(root.left, arr)
storeLeaf(root.right, arr)
# Function to find the K smallest
# nodes of the Binary Tree
def KSmallest(root: Node,
k: int) -> None:
arr = []
storeLeaf(root, arr)
# Sorting the Leaf
# nodes array
arr.sort()
# Loop to print the K smallest
# Leaf nodes of the array
for i in range(k):
if (i < len(arr)):
print(arr[i], end = " ")
else:
break
# Driver Code
if __name__ == "__main__":
# Construct binary tree
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.left.left = Node(21)
root.left.right = Node(5)
root.left.right.right = Node(8)
root.right = Node(3)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.right.right = Node(19)
# Function Call
KSmallest(root, 3)
# This code is contributed by sanjeev2552
C#
// C# program of the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Structure of
// binary tree node
class Node
{
public int data;
public Node left, right;
};
// Function to create new node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Utility function which calculates
// smallest three nodes of all leaf nodes
static List<int> storeLeaf(Node root,
List<int> arr)
{
if (root == null)
return arr;
// Check if current root is a leaf node
if (root.left == null &&
root.right == null)
{
arr.Add(root.data);
return arr;
}
// Traverse the left
// and right subtree
arr = storeLeaf(root.left, arr);
arr = storeLeaf(root.right, arr);
return arr;
}
// Function to find the K smallest
// nodes of the Binary Tree
static void KSmallest(Node root, int k)
{
List<int> arr = new List<int>();
arr = storeLeaf(root, arr);
// Sorting the Leaf nodes array
arr.Sort();
// Loop to print the K smallest
// Leaf nodes of the array
for(int i = 0; i < k; i++)
{
if (i < arr.Count)
{
Console.Write(arr[i] + " ");
}
else
{
break;
}
}
}
// Driver Code
public static void Main(String[] args)
{
// Construct binary tree
Node root = newNode(1);
root.left = newNode(2);
root.left.left = newNode(4);
root.left.left.left = newNode(21);
root.left.right = newNode(5);
root.left.right.right = newNode(8);
root.right = newNode(3);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.right.right = newNode(19);
// Function call
KSmallest(root, 3);
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// JavaScript program for the above approach
// Structure of binary tree node
class Node
{
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// Function to create new node
function newNode(data)
{
let temp = new Node(data);
return temp;
}
// Utility function which calculates
// smallest three nodes of all leaf nodes
function storeLeaf(root, arr)
{
if (root == null)
return arr;
// Check if current root is a leaf node
if (root.left == null &&
root.right == null)
{
arr.push(root.data);
return arr;
}
// Traverse the left
// and right subtree
arr = storeLeaf(root.left, arr);
arr = storeLeaf(root.right, arr);
return arr;
}
// Function to find the K smallest
// nodes of the Binary Tree
function KSmallest(root, k)
{
let arr = [];
arr = storeLeaf(root, arr);
// Sorting the Leaf nodes array
arr.sort(function(a, b){return a - b});
// Loop to print the K smallest
// Leaf nodes of the array
for(let i = 0; i < k; i++)
{
if (i < arr.length)
{
document.write(arr[i] + " ");
}
else
{
break;
}
}
}
// Construct binary tree
let root = newNode(1);
root.left = newNode(2);
root.left.left = newNode(4);
root.left.left.left = newNode(21);
root.left.right = newNode(5);
root.left.right.right = newNode(8);
root.right = newNode(3);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.right.right = newNode(19);
// Function call
KSmallest(root, 3);
</script>
Time Complexity: O(N + L*logL), Here L is the count of leaf nodes and N is the number of nodes.
Auxiliary Space: O(L + logN)
Similar Reads
Closest leaf to a given node in Binary Tree Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x
12 min read
Find sum of all left leaves in a given Binary Tree Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then a
15+ min read
Print all nodes in a binary tree having K leaves Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
7 min read
Find sum of all right leaves in a given Binary Tree Given a Binary Tree, the task is to find the sum of all right leaf nodes in it. Examples : Example1: Sum of all the right leaf nodes in the below tree is 2 + 5 + 7 = 15 Example2: Sum of all the right leaf nodes in the below tree is 5 + 8 = 13 Table of Content [Expected Approach - 1] Using Recursion
14 min read
Kth Smallest element in a Perfect Binary Search Tree Given a Perfect BST with N nodes and an integer K, the task is to find the Kth smallest element is present in the tree. Example: Input: K = 3, N = 15 50 / \ 30 70 / \ / \ 20 40 60 80 /\ /\ /\ / \ 14 25 35 45 55 65 75 85 Output: 25 Explanation: The 3rd smallest element in the given BST is 25 Input: K
12 min read