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
Compare Trees Early Exit
00:00
5 left

Compare Trees Early Exit

EasyPython

Problem

Beckman Coulter Diagnostics software can represent analyzer configuration data as binary trees. Given two such trees, determine whether they are identical, and stop traversing immediately when a difference is found.

Two trees are identical when corresponding nodes have the same integer value and the same structure. A missing child is represented by None.

Formal Specification

Implement compare_trees(tree1, tree2). Each tree is either None or a dictionary with exactly three fields: value, left, and right. The left and right fields contain another tree or None. Return a boolean: True if the trees are identical, otherwise False.

Your implementation must short-circuit. Once a corresponding pair of nodes differs in value or structure, it must return without visiting any remaining subtrees.

Constraints

  • Each tree contains between 0 and 10^5 nodes.
  • Node values are integers from -10^9 through 10^9.
  • Tree height can be as large as the number of nodes.
  • Every non-empty node has the fields value, left, and right.

Function Signature

def compare_trees(tree1, tree2):
Interviewer

Your question is Compare Trees Early Exit. 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.