Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Subtree of a Binary Tree
00:00
5 left

Subtree of a Binary Tree

HardPython

Problem

Sage software may represent hierarchical structures such as account or reporting trees. Given two binary trees, determine whether the second tree appears as an exact subtree of the first.

A tree is encoded as either None for an empty tree or [value, left, right], where left and right use the same format. A subtree must match both node values and structure, including empty-child positions. Return True if sub_root occurs in root, otherwise return False.

Because the trees can contain many repeated values, avoid relying only on value sequences. Serialize null children explicitly, then use an efficient pattern-matching algorithm to search for the serialized sub_root inside the serialized root.

Formal Specification

Implement is_subtree(root, sub_root).

  • Input: Two binary trees represented as nested lists or None.
  • Output: A Boolean indicating whether sub_root is an exact subtree of root.
  • Values are integers and may be negative or repeated.

Constraints

  • 0 <= number of nodes in either tree <= 100000
  • -10^9 <= each node value <= 10^9
  • Values may repeat
  • Every tree is represented as [value, left, right] or None
  • An empty sub_root is considered a subtree of any root

Function Signature

def is_subtree(root, sub_root):
Interviewer

Your question is Subtree of a Binary Tree. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.