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.
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>usingnamespacestd;// Print the leaf node from // the given preorder of BST.boolisLeaf(vector<int>pre,int&i,intn,intmin,intmax){// If all elements is checked return if(i>=n)returnfalse;// Check if node is leaf or notif(pre[i]>min&&pre[i]<max){i++;// Left and right node status if both are false// then current node is leaf nodeboolleft=isLeaf(pre,i,n,min,pre[i-1]);boolright=isLeaf(pre,i,n,pre[i-1],max);// if no node found at left and right side print dataif(!left&&!right)cout<<pre[i-1]<<" ";returntrue;}returnfalse;}// Function to print all leafsvoidprintLeaves(vector<int>preorder,intn){inti=0;isLeaf(preorder,i,n,INT_MIN,INT_MAX);}intmain(){intn=5;// Array represantion of below BST// 10// / \ // 6 13// / \ // 2 7vector<int>preorder{10,6,2,7,13};printLeaves(preorder,n);return0;}
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.intisLeaf(intpre[],int*i,intn,intmin,intmax){// If all elements are checked return if(*i>=n)return0;// Check if node is leaf or notif(pre[*i]>min&&pre[*i]<max){(*i)++;// Left and right node status, if both are false// then current node is leaf nodeintleft=isLeaf(pre,i,n,min,pre[*i-1]);intright=isLeaf(pre,i,n,pre[*i-1],max);// if no node found at left and right side print dataif(!left&&!right)printf("%d ",pre[*i-1]);return1;}return0;}// Function to print all leavesvoidprintLeaves(intpreorder[],intn){inti=0;isLeaf(preorder,&i,n,INT_MIN,INT_MAX);}intmain(){intn=5;// Array representation of below BST// 10// / \ // 6 13// / \ // 2 7intpreorder[]={10,6,2,7,13};printLeaves(preorder,n);return0;}
Java
// Recursive Java program to find leaf // nodes from given preorder traversalimportjava.util.*;classGfG{// Print the leaf node from // the given preorder of BST.staticbooleanisLeaf(List<Integer>pre,int[]i,intn,intmin,intmax){// If all elements is checked return if(i[0]>=n)returnfalse;// Check if node is leaf or notif(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 nodebooleanleft=isLeaf(pre,i,n,min,pre.get(i[0]-1));booleanright=isLeaf(pre,i,n,pre.get(i[0]-1),max);// if no node found at left and right side print dataif(!left&&!right)System.out.print(pre.get(i[0]-1)+" ");returntrue;}returnfalse;}// Function to print all leavesstaticvoidprintLeaves(List<Integer>preorder,intn){int[]i={0};// Call utility function to print all leavesisLeaf(preorder,i,n,Integer.MIN_VALUE,Integer.MAX_VALUE);}publicstaticvoidmain(String[]args){intn=5;// Array representation of below BST// 10// / \ // 6 13// / \// 2 7List<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.defis_leaf(pre,i,n,min_val,max_val):# If all elements is checked return ifi[0]>=n:returnFalse# Check if node is leaf or notifmin_val<pre[i[0]]<max_val:i[0]+=1# Left and right node status if both are false# then current node is leaf nodeleft=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 dataifnotleftandnotright:print(pre[i[0]-1],end=" ")returnTruereturnFalse# Function to print all leavesdefprint_leaves(preorder,n):i=[0]# Call utility function to print all leavesis_leaf(preorder,i,n,float('-inf'),float('inf'))if__name__=="__main__":n=5# Array representation of below BST# 10# / \ # 6 13# / \# 2 7preorder=[10,6,2,7,13]print_leaves(preorder,n)
C#
// Recursive C# program to find leaf // nodes from given preorder traversalusingSystem;usingSystem.Collections.Generic;classGfG{// Print the leaf node from // the given preorder of BST.staticboolIsLeaf(List<int>pre,refinti,intn,intmin,intmax){// If all elements is checked return if(i>=n)returnfalse;// Check if node is leaf or notif(pre[i]>min&&pre[i]<max){i++;// Left and right node status if both are false// then current node is leaf nodeboolleft=IsLeaf(pre,refi,n,min,pre[i-1]);boolright=IsLeaf(pre,refi,n,pre[i-1],max);// if no node found at left and right side print dataif(!left&&!right)Console.Write(pre[i-1]+" ");returntrue;}returnfalse;}// Function to print all leavesstaticvoidPrintLeaves(List<int>preorder,intn){inti=0;IsLeaf(preorder,refi,n,int.MinValue,int.MaxValue);}staticvoidMain(){intn=5;// Array representation of below BST// 10// / \ // 6 13// / \// 2 7List<int>preorder=newList<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.functionisLeaf(pre,i,n,min,max){// If all elements is checked return if(i[0]>=n)returnfalse;// Check if node is leaf or notif(pre[i[0]]>min&&pre[i[0]]<max){i[0]++;// Left and right node status if both are false// then current node is leaf nodeletleft=isLeaf(pre,i,n,min,pre[i[0]-1]);letright=isLeaf(pre,i,n,pre[i[0]-1],max);// if no node found at left and right side print dataif(!left&&!right)console.log(pre[i[0]-1]);returntrue;}returnfalse;}// Function to print all leavesfunctionprintLeaves(preorder,n){leti=[0];isLeaf(preorder,i,n,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);}letn=5;// Array representation of below BST// 10// / \ // 6 13// / \// 2 7letpreorder=[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.
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.