Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) (original) (raw)

Last Updated : 10 Oct, 2024

Given **Preorder traversal of a Binary Search Tree. Then the task is to print **leaf nodes of the Binary Search Tree from the given preorder.

**Examples :

**Input : preorder[] = {890, 325, 290, 530, 965};
**Output : 290 530 965
**Explanation: Below is the representation of BST using preorder array.

Leaf-nodes-from-Preorder-of-a-Binary-Search-Tree

**Approach:

To identify **leaf nodes from a given **preorder traversal of a binary search tree ****(BST)**, we employ a recursive approach that utilizes the properties of BSTs and preorder traversal. The algorithm maintains two variables, **min and **max, which define the valid range for each node based on its position in the tree. Starting with an index i set to zero, we traverse the preorder array. For each node, we check if its value lies within the specified range. if so, we consider it a valid node. We then increment the index and make recursive calls to check for potential **left and **right children, adjusting the **min and **max values accordingly. If both recursive calls return **false, indicating that the node has no children, we store the node’s value as it is a leaf.

Below is the implementation of the above approach:

C++ `

// Recursive C++ program to find leaf // nodes from given preorder traversal

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

// Print the leaf node from // the given preorder of BST. bool isLeaf(vector pre, int &i, int n, int min, int max) {

  // If all elements is checked return  
  if (i >= n) 
    return false;

  // Check if node is leaf or not
if (pre[i] > min && pre[i] < max) {
    i++;
    
      // Left and right node status if both are false
      // then current node is leaf node
    bool left = isLeaf(pre, i, n, min, pre[i-1]);
    bool right = isLeaf(pre, i, n, pre[i-1], max);
    
      // if no node found at left and right side print data
    if (!left && !right) 
        cout << pre[i-1] << " ";
        
    return true;
}
return false;

}

// Function to print all leafs void printLeaves(vector preorder, int n) { int i = 0;

isLeaf(preorder, i, n, INT_MIN, INT_MAX);

}

int main() { int n = 5;

  // Array represantion of below BST
  //        10
  //       /  \ 
//      6    13
//     / \
  //    2   7
  vector<int> preorder{10, 6, 2, 7, 13};
printLeaves(preorder, n);    
return 0;

}

C

// Recursive C program to find leaf // nodes from given preorder traversal

#include <stdio.h> #include <limits.h>

// Print the leaf node from // the given preorder of BST. int isLeaf(int pre[], int *i, int n, int min, int max) {

// If all elements are checked return  
if (*i >= n)
    return 0;

// Check if node is leaf or not
if (pre[*i] > min && pre[*i] < max) {
    (*i)++;

    // Left and right node status, if both are false
    // then current node is leaf node
    int left = isLeaf(pre, i, n, min, pre[*i - 1]);
    int right = isLeaf(pre, i, n, pre[*i - 1], max);

    // if no node found at left and right side print data
    if (!left && !right)
        printf("%d ", pre[*i - 1]);

    return 1;
}
return 0;

}

// Function to print all leaves void printLeaves(int preorder[], int n) { int i = 0;

isLeaf(preorder, &i, n, INT_MIN, INT_MAX);

}

int main() { int n = 5;

// Array representation of below BST
//        10
//       /  \ 
//      6    13
//     / \
//    2   7
int preorder[] = {10, 6, 2, 7, 13};
printLeaves(preorder, n);
return 0;

}

Java

// Recursive Java program to find leaf // nodes from given preorder traversal

import java.util.*;

class GfG {

// Print the leaf node from 
// the given preorder of BST.
static boolean isLeaf(List<Integer> pre, int[] i, int n, int min, int max) {
    
    // If all elements is checked return  
    if (i[0] >= n)
        return false;

    // Check if node is leaf or not
    if (pre.get(i[0]) > min && pre.get(i[0]) < max) {
        i[0]++;
        
        // Left and right node status if both are false
        // then current node is leaf node
        boolean left = isLeaf(pre, i, n, min, pre.get(i[0] - 1));
        boolean right = isLeaf(pre, i, n, pre.get(i[0] - 1), max);

        // if no node found at left and right side print data
        if (!left && !right)
            System.out.print(pre.get(i[0] - 1) + " ");

        return true;
    }
    return false;
}

// Function to print all leaves
static void printLeaves(List<Integer> preorder, int n) {
    int[] i = {0};

    // Call utility function to print all leaves
    isLeaf(preorder, i, n, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

public static void main(String[] args) {
    int n = 5;
    
    // Array representation of below BST
    //        10
    //       /  \ 
    //      6    13
    //     / \
    //    2   7
    List<Integer> preorder = Arrays.asList(10, 6, 2, 7, 13);
    printLeaves(preorder, n);
}

}

Python

Recursive Python program to find leaf

nodes from given preorder traversal

Print the leaf node from

the given preorder of BST.

def is_leaf(pre, i, n, min_val, max_val):

# If all elements is checked return  
if i[0] >= n:
    return False

# Check if node is leaf or not
if min_val < pre[i[0]] < max_val:
    i[0] += 1
    
    # Left and right node status if both are false
    # then current node is leaf node
    left = is_leaf(pre, i, n, min_val, pre[i[0] - 1])
    right = is_leaf(pre, i, n, pre[i[0] - 1], max_val)

    # if no node found at left and right side print data
    if not left and not right:
        print(pre[i[0] - 1], end=" ")

    return True
return False

Function to print all leaves

def print_leaves(preorder, n): i = [0]

# Call utility function to print all leaves
is_leaf(preorder, i, n, float('-inf'), float('inf'))

if name == "main": n = 5

# Array representation of below BST
#        10
#       /  \ 
#      6    13
#     / \
#    2   7
preorder = [10, 6, 2, 7, 13]
print_leaves(preorder, n)

C#

// Recursive C# program to find leaf // nodes from given preorder traversal

using System; using System.Collections.Generic;

class GfG {

// Print the leaf node from 
// the given preorder of BST.
static bool IsLeaf(List<int> pre, ref int i, int n, 
                   int min, int max) {

    // If all elements is checked return  
    if (i >= n) 
        return false;

    // Check if node is leaf or not
    if (pre[i] > min && pre[i] < max) {
        i++;
        
        // Left and right node status if both are false
        // then current node is leaf node
        bool left = IsLeaf(pre, ref i, n, min, pre[i - 1]);
        bool right = IsLeaf(pre, ref i, n, pre[i - 1], max);

        // if no node found at left and right side print data
        if (!left && !right)
            Console.Write(pre[i - 1] + " ");

        return true;
    }
    return false;
}

// Function to print all leaves
static void PrintLeaves(List<int> preorder, int n) {
    int i = 0;
    
    IsLeaf(preorder, ref i, n, int.MinValue, int.MaxValue);
}

static void Main() {
    int n = 5;
    
    // Array representation of below BST
    //        10
    //       /  \ 
    //      6    13
    //     / \
    //    2   7
    List<int> preorder = new List<int> { 10, 6, 2, 7, 13 };
    PrintLeaves(preorder, n);
}

}

JavaScript

// Recursive JavaScript program to find leaf // nodes from given preorder traversal

// Print the leaf node from // the given preorder of BST. function isLeaf(pre, i, n, min, max) {

// If all elements is checked return  
if (i[0] >= n)
    return false;

// Check if node is leaf or not
if (pre[i[0]] > min && pre[i[0]] < max) {
    i[0]++;
    
    // Left and right node status if both are false
    // then current node is leaf node
    let left = isLeaf(pre, i, n, min, pre[i[0] - 1]);
    let right = isLeaf(pre, i, n, pre[i[0] - 1], max);

    // if no node found at left and right side print data
    if (!left && !right)
        console.log(pre[i[0] - 1]);

    return true;
}
return false;

}

// Function to print all leaves function printLeaves(preorder, n) { let i = [0];

isLeaf(preorder, i, n, Number.MIN_SAFE_INTEGER, 
                    Number.MAX_SAFE_INTEGER);

}

let n = 5;

// Array representation of below BST // 10 // / \ // 6 13 // /
// 2 7 let preorder = [10, 6, 2, 7, 13]; printLeaves(preorder, n);

`

**Time Complexity: O(n), As we are traversing the **BST only once.
**Auxiliary Space: O(h), here h is the height of the BST and the extra space is used in the recursion call stack.

**Related article: