Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Reverse a Binary Tree
00:00
5 left

Reverse a Binary Tree

EasyPython

Problem

Write a function to reverse a binary tree.

The function receives the root of a binary tree and must swap the left and right children of every node in place, returning the original root. Use TreeNode objects with val, left, and right fields; test inputs and outputs use level-order arrays with null for missing children.

For example, [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1], and an empty tree remains empty.

Constraints

  • 0 <= number of nodes <= 10^3
  • Each node value is an integer
  • The input tree is represented by TreeNode objects
  • The transformation must modify the existing nodes in place

Function Signature

def reverse_binary_tree(root):
Interviewer

Your question is Reverse 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
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.