LeetCode 2764: Is Array a Preorder of Some Binary Tree Solution
Master LeetCode problem 2764 (Is Array a Preorder of Some Binary 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.
2764. Is Array a Preorder of Some Binary Tree
Problem Explanation
Explanation
To determine if an array is a preorder traversal of some binary tree, we can utilize the property of preorder traversal where the root node comes before its children nodes. We can construct the binary tree using the given preorder array and then compare it with the original array to check if they are the same.
The algorithm involves simulating the process of constructing a binary tree from the preorder array. We maintain a stack to keep track of the nodes as we traverse the array. If the constructed binary tree matches the original array, then the given array is a preorder traversal of some binary tree.
- We iterate through the input array and construct a binary tree using a stack.
- At each step, we push the current node to the stack and move to the left child until we reach a leaf node.
- If we encounter a null value in the array, we pop the stack until we find a node with a right child.
- We continue this process until we reach the end of the array.
Time complexity: O(n) where n is the size of the input array. Space complexity: O(n) for the stack.
Solution Code
import java.util.Stack;
class Solution {
public boolean isValidPreorder(int[] preorder) {
Stack<Integer> stack = new Stack<>();
int root = Integer.MIN_VALUE;
for (int num : preorder) {
if (num < root) {
return false;
}
while (!stack.isEmpty() && num > stack.peek()) {
root = stack.pop();
}
stack.push(num);
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2764 (Is Array a Preorder of Some Binary Tree)?
This page provides optimized solutions for LeetCode problem 2764 (Is Array a Preorder of Some Binary 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 2764 (Is Array a Preorder of Some Binary Tree)?
The time complexity for LeetCode 2764 (Is Array a Preorder of Some Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2764 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2764 in Java, C++, or Python.