Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Next article icon

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

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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<int> 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<int> 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); 

Output
2 7 13 

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:

  • Leaf nodes from Preorder of a Binary Search Tree

Next Article
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)

V

vishal22091998
Improve
Article Tags :
  • Misc
  • Tree
  • Recursion
  • DSA
Practice Tags :
  • Misc
  • Recursion
  • Tree

Similar Reads

    Binary Search Tree
    A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the node’s value. All nodes in the right subtree of a node contain values s
    4 min read
    Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
    Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
    3 min read
    Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
    Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
    15 min read
    Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
    Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
    10 min read
    Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
    10 min read
    Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
    10 min read
    Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences