Check if a given array can represent Preorder Traversal of Binary Search Tree - GeeksforGeeks
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n).
public static boolean isValid(int arr[], int start, int end, int min, int max)
{
if (end < start || start >= arr.length)
return true;
int root = arr[start];
if (root < min || root > max)
return false;
int i = start + 1;
for (i = start + 1; i < end; i++)
{
if (arr[i] < min || arr[i] > max)
return false;
if (root < arr[i])
break;
}
return isValid(arr, start + 1, i - 1, min, arr[start]) && isValid(arr, i, end, arr[start], max);
}
Related: LeetCode 255 - Verify Preorder Sequence in Binary Search Tree
Read full article from Check if a given array can represent Preorder Traversal of Binary Search Tree - GeeksforGeeks
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n).
Input: pre[] = {2, 4, 3} Output: true Given array can represent preorder traversal of below tree 2 \ 4 / 3 Input: pre[] = {2, 4, 1} Output: false Given array cannot represent preorder traversal of a Binary Search Tree.
http://www.snippetexample.com/2015/03/verify-preorder-sequence-in-binary-search-tree/
The pre-order sequence of binary tree can form a sorted stack. So lets break it in a few “SIMPLE” steps as follows:
The pre-order sequence of binary tree can form a sorted stack. So lets break it in a few “SIMPLE” steps as follows:
1. Push to stack till you get higher element than the topmost element of the stack. [i.e. you keep pushing till you hit the leftmost leaf]
2. If you find current value which is greater than the TOP of Stack, POP till you hit higher element, and also mark the last poped value, which is your variable (Left_Tree_Highest). This variable is used to check whether the order is correct or not.
3. In all the steps, if you find current element lesser than Left_Tree_Highest, then your tree is not a Binary Search Tree and it should return “NO”.
2. If you find current value which is greater than the TOP of Stack, POP till you hit higher element, and also mark the last poped value, which is your variable (Left_Tree_Highest). This variable is used to check whether the order is correct or not.
3. In all the steps, if you find current element lesser than Left_Tree_Highest, then your tree is not a Binary Search Tree and it should return “NO”.
public
static
String checkBST(
int
[] preOrderArray){
Stack<Integer> s =
new
Stack<Integer>();
int
lower = -
1
;
for
(
int
i=
0
;i<preOrderArray.length;i++){
if
(lower>-
1
&& preOrderArray[i] < lower){
return
"NO"
;
}
while
(!s.isEmpty() && s.peek()<preOrderArray[i]){
lower = s.pop();
}
s.push(preOrderArray[i]);
}
return
"YES"
;
}
public boolean verifyPreorder(int[] preorder) {
int low = Integer.MIN_VALUE;
Stack<Integer> st = new Stack<>();
for(int p : preorder){
if (p < low)
return false;
while (!st.empty()&& st.peek() < p)
low = st.pop();
st.push(p);
}
return true;
}
An Efficient Solution can solve this problem in O(n) time. The idea is to use a stack. This problem is similar toNext (or closest) Greater Element problem. Here we find next greater element and after finding next greater, if we find a smaller element, then return false.
1) Create an empty stack. 2) Initialize root as INT_MIN. 3) Do following for every element pre[i] a) If pre[i] is greater than current root, return false. b) Keep removing elements from stack while pre[i] is greater then stack top. Make the last removed item as new root (to be compared next). At this point, pre[i] is greater than the removed root (That is why if we see a smaller element in step a), we return false) c) push pre[i] to stack (All elements in stack are in decreasing order)
bool
canRepresentBST(
int
pre[],
int
n)
{
// Create an empty stack
stack<
int
> s;
// Initialize current root as minimum possible
// value
int
root = INT_MIN;
// Traverse given array
for
(
int
i=0; i<n; i++)
{
// If we find a node who is on right side
// and smaller than root, return false
if
(pre[i] < root)
return
false
;
// If pre[i] is in right subtree of stack top,
// Keep removing items smaller than pre[i]
// and make the last removed item as new
// root.
while
(!s.empty() && s.top()<pre[i])
{
root = s.top();
s.pop();
}
// At this point either stack is empty or
// pre[i] is smaller than root, push pre[i]
s.push(pre[i]);
}
return
true
;
}
A Simple Solution is to do following for every node pre[i] starting from first one.
1) Find the first greater value on right side of current node. Let the index of this node be j. Return true if following conditions hold. Else return false (i) All values after the above found greater value are greater than current node. (ii) Recursive calls for the subarrays pre[i+1..j-1] and pre[j+1..n-1] also return true.
Time Complexity of the above solution is O(n2)
Not efficient:
System.out.println(isValid(arr, 0, arr.length, Integer.MIN_VALUE, Integer.MAX_VALUE));public static boolean isValid(int arr[], int start, int end, int min, int max)
{
if (end < start || start >= arr.length)
return true;
int root = arr[start];
if (root < min || root > max)
return false;
int i = start + 1;
for (i = start + 1; i < end; i++)
{
if (arr[i] < min || arr[i] > max)
return false;
if (root < arr[i])
break;
}
return isValid(arr, start + 1, i - 1, min, arr[start]) && isValid(arr, i, end, arr[start], max);
}
Related: LeetCode 255 - Verify Preorder Sequence in Binary Search Tree
Read full article from Check if a given array can represent Preorder Traversal of Binary Search Tree - GeeksforGeeks