Geeksforgeeks

X

DAYS

:

HOUR

:

MINS

:

SEC

Error

Copied to Clipboard

Given an array **arr[ ] **of size **N **consisting of **distinct** integers, write a program that returns **1** if given array can represent preorder traversal of a possible BST, else returns** 0**.

**Example 1:**

Input:N = 3 arr = {2, 4, 3}Output:1Explaination:Given arr[] can represent preorder traversal of following BST: 2 \ 4 / 3

**Example 2:**

**Input:**
N = 3
Arr = {2, 4, 1}
**Output:** 0
**Explaination:** Given arr[] cannot represent
preorder traversal of a BST.

**Your Task:**

You don't need to read input or print anything. Your task is to complete the function **canRepresentBST()** which takes the array a**rr[]** and its size **N **as input parameters and returns **1** if given array can represent preorder traversal of a BST, else returns** 0**.

**Expected Time Complexity:** O(N)

**Expected Auxiliary Space:** O(N)

**Constraints:**

1 ≤ N ≤ 10^{5}

0 ≤ arr[i] ≤ 10^{5}

We are replacing the old Disqus forum with the new Discussions section given below.

Click here to view old Disqus comments.

Click here to view old Disqus comments.

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

YesLoading...

Preorder Traversal and BST

...