Leaf nodes from Preorder of a Binary Search Tree

Given a preorder traversal of a Binary Search Tree, A of length N.

Return an array of integers representing the leaf nodes of the Binary Search Tree from the given preorder.

You can return the leaf nodes in any order.


Input Format:

The first and the only argument of input contains an integer array, A, of size N, representing the preorder traversal of the Binary Search Tree.

Output Format:

Return an array of integers representing the leaf nodes.

Constraints:

1 <= N <= 1e5
1 <= A[i] <= 1e7

Examples:

Input 1:
    A = [3, 2, 4]

Output 1:
    [2, 4]

Explanation 1:
    The tree that gives this preorder can be:
        3
       / \
      2   4
    The leaf nodes are : 2 and 4.
    
    Note: [4, 2] is also an acceptable answer.

Input 2:
    A = [4, 2, 1, 3, 5]

Output 2:
    [3, 5, 1]

Explanation 2:
    The tree that gives this preorder can be:
        4
       / \
      2   5
     / \
    1   3
    
    Note: [1, 3, 5], [5, 3, 1] etc. are also acceptable.
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Leaf nodes from Preorder of a Binary Search Tree on Interview Code Editor
Sign Up
to access hints and editorial solutions for Leaf nodes from Preorder of a Binary Search Tree

Discussion


Loading...
Click here to start solving coding interview questions