LeetCode 255: Verify Preorder Sequence in Binary Search Tree Solution
Master LeetCode problem 255 (Verify Preorder Sequence in Binary Search Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
255. Verify Preorder Sequence in Binary Search Tree
Problem Explanation
Explanation:
The problem asks us to determine if a given array represents the preorder traversal of a valid binary search tree (BST).
To solve this problem, we can use a stack to simulate the traversal of the BST. We iterate through the array and keep track of the nodes that we have seen so far. If we encounter a node greater than the previous node, we know that we have entered the right subtree of some node. We then pop all the nodes from the stack that are smaller than the current node because all the nodes in the left subtree have already been visited.
At the end, if we have correctly traversed the entire array without violating the BST property, then the array represents the preorder traversal of a valid BST.
: :
Solution Code
class Solution {
public boolean verifyPreorder(int[] preorder) {
Stack<Integer> stack = new Stack<>();
int low = Integer.MIN_VALUE;
for (int num : preorder) {
if (num < low) {
return false;
}
while (!stack.isEmpty() && num > stack.peek()) {
low = stack.pop();
}
stack.push(num);
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 255 (Verify Preorder Sequence in Binary Search Tree)?
This page provides optimized solutions for LeetCode problem 255 (Verify Preorder Sequence in Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 255 (Verify Preorder Sequence in Binary Search Tree)?
The time complexity for LeetCode 255 (Verify Preorder Sequence in Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 255 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 255 in Java, C++, or Python.