Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Mirror a Binary Tree

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Mirror a Binary Tree. Start with the requirements on the right.

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.

Problem

Fireblocks policy evaluation can represent approval rules as a binary tree. Given the root of a binary policy tree, mirror the tree in place by recursively swapping the left and right children of every node, then return the original root.

The operation must reuse the existing TreeNode objects. Do not create replacement nodes or copy the tree. The interviewer may also ask how your approach behaves when the tree is highly unbalanced.

Formal Specification

Assume each node has the following interface:

  • node.val: an integer rule identifier
  • node.left: a TreeNode or None
  • node.right: a TreeNode or None

Implement mirror_policy_tree(root), where root is a TreeNode or None. Return the same root object after mutating the entire tree. Test inputs and expected outputs use nested objects with val, left, and right fields to represent TreeNode instances.

Constraints

  • 0 <= number of nodes <= 10^5
  • -10^9 <= node.val <= 10^9
  • Each node has at most two children
  • The input is a valid acyclic binary tree
  • The recursive solution should use only the call stack beyond the tree nodes

Function Signature

def mirror_policy_tree(root):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output