Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2764: Is Array a Preorder of Some ‌Binary Tree

In this guide, we solve Leetcode #2764 Is Array a Preorder of Some ‌Binary Tree in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a 0-indexed integer 2D array nodes, your task is to determine if the given array represents the preorder traversal of some binary tree. For each index i, nodes[i] = [id, parentId], where id is the id of the node at the index i and parentId is the id of its parent in the tree (if the node has no parent, then parentId == -1).

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Stack, Tree, Depth-First Search, Binary Tree

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

Input: nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] Output: true Explanation: The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4].

Python Solution

class Solution: def isPreorder(self, nodes: List[List[int]]) -> bool: def dfs(i: int) -> int: nonlocal k if i != nodes[k][0]: return False k += 1 return all(dfs(j) for j in g[i]) g = defaultdict(list) for i, p in nodes: g[p].append(i) k = 0 return dfs(nodes[0][0]) and k == len(nodes)

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy