Leaf nodes from Preorder of a Binary Search Tree

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


Input : preorder[] = {890, 325, 290, 530, 965};
Output : 290 530 965
Explanation : Tree represented is,
     /   \
  325    965
  /  \
290   530

Input : preorder[] = { 3, 2, 4 };
Output : 2 4

Method 1: (Simple)

The idea is to find Iorder, then traverse the tree in preorder fashion (using both inorder and postorder traversals) and while traversing print leaf nodes.

How to traverse in preorder fashion using two arrays representing inorder and preorder traversals?
We iterate the preorder array and for each element find that element in the inorder array. For searching, we can use binary search, since inorder traversal of binary search tree is always sorted. Now, for each element of preorder array, in binary search we set the range [L, R].
And when L == R, leaf node is found. So, initially, L = 0 and R = n – 1 for first element (i.e root) of preorder array. Now, to search for element on the left subtree of root, set L = 0 and R = index of root – 1. Also, for all element of right subtree set L = index of root + 1 and R = n -1.
Recursively, follow this, until L == R.

Below is C++ implementation of this approach:

// C++ program to print leaf node from
// preorder of binary search tree.
using namespace std;

// Binary Search
int binarySearch(int inorder[], int l, int r, int d)
    int mid = (l + r)>>1;

    if (inorder[mid] == d)
        return mid;

    else if (inorder[mid] > d)
        return binarySearch(inorder, l, mid - 1, d);

        return binarySearch(inorder, mid + 1, r, d);

// Function to print Leaf Nodes by doing preorder
// traversal of tree using preorder and inorder arrays.
void leafNodesRec(int preorder[], int inorder[],
                  int l, int r, int *ind, int n)
    // If l == r, therefore no right or left subtree.
    // So, it must be leaf Node, print it.
    if(l == r)
        printf("%d ", inorder[l]);
        *ind = *ind + 1;

    // If array is out of bound, return.
    if (l < 0 || l > r || r >= n)

    // Finding the index of preorder element
    // in inorder array using binary search.
    int loc = binarySearch(inorder, l, r, preorder[*ind]);

    // Incrementing the index.
    *ind = *ind + 1;

    // Finding on the left subtree.
    leafNodesRec(preorder, inorder, l, loc - 1, ind, n);

    // Finding on the right subtree.
    leafNodesRec(preorder, inorder, loc + 1, r, ind, n);

// Finds leaf nodes from given preorder traversal.
void leafNodes(int preorder[], int n)
    int inorder[n];  // To store inorder traversal

    // Copy the preorder into another array.
    for (int i = 0; i < n; i++)
        inorder[i] = preorder[i];

    // Finding the inorder by sorting the array.
    sort(inorder, inorder + n);

    // Point to the index in preorder.
    int ind = 0;

    // Print the Leaf Nodes.
    leafNodesRec(preorder, inorder, 0, n - 1, &ind, n);

// Driven Program
int main()
    int preorder[] = { 890, 325, 290, 530, 965 };
    int n = sizeof(preorder)/sizeof(preorder[0]);

    leafNodes(preorder, n);
    return 0;


290 530 965

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Method 2:(using Stack)

The idea is to use the property of the Binary Search Tree and stack.
Traverse the array using two pointer i and j to the array, initially i = 0 and j = 1. Whenever a[i] > a[j], we can say a[j] is left part of a[i], since preorder traversal follows Visit -> Left -> Right. So, we push a[i] into the stack.
For those points voilating the rule, we start to pop element from the stack till a[i] > top element of the stack and break when it doesn’t and print the corresponding jth value.

1. Set i = 0, j = 1.
2. Traverse the preorder array.
3. If a[i] > a[j], push a[i] to the stack.
4. Else
   While (stack is not empty)
     if (a[j] > top of stack)
       pop element from the stack;
       set found = true;
5. if (found == true)
     print a[i];

How this algorithm works?
Preorder traversal traverse in the order: Visit, Left, Right.
And we know left node of any node in BST is always less than node. So preorder traversal will first traverse from root to leftmost node. Therefore, preorder will be in decreasing order first. Now, after decreasing order there may be node which is greater or which break the decreasing order. So, there can be case like this :

In case 1, 20 is leaf node whereas in case 2, 20 is not the leaf node.
So, our problem is how to identify if we have to print 20 as leaf node or not?
This is solved using stack.
While running above algorithm on case 1 and case 2, when i = 2 and j = 3, state of stack will be same in both the case :

So, node 65 will pop 20 and 50 from the stack. This is because 65 is the right child of a node which is before 20. This information we store using found varible. So, 20 is a root node.
While in case 2, 40 will not able to pop any element from the stack. Because 40 is right node of a node which is after 20. So, 20 is not a leaf node.

Note: In the algorithm, we will not be able to check condition of leaf node of rightmost node or rightmost element of the preorder. So, simply print the rightmost node because we know this will always be leaf node in preorder traversal.

Below is C++ implementation of this approach:

// Stack based C++ program to print leaf nodes
// from preorder traversal.
using namespace std;

// Print the leaf node from the given preorder of BST.
void leafNode(int preorder[], int n)
    stack<int> s;
    for (int i = 0, j = 1; j < n; i++, j++)
        bool found = false;

        if (preorder[i] > preorder[j])

            while (!s.empty())
                if (preorder[j] > s.top())
                    found = true;

        if (found)
            cout << preorder[i] << " ";

    // Since rightmost element is always leaf node.
    cout << preorder[n - 1];

// Driver code
int main()
    int preorder[] = { 890, 325, 290, 530, 965 };
    int n = sizeof(preorder)/sizeof(preorder[0]);

    leafNode(preorder, n);
    return 0;
290 530 965

Time Complexity: O(n)

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

4.4 Average Difficulty : 4.4/5.0
Based on 7 vote(s)