Invert Binary Tree
LeetCode Problem #226 (Easy)
Problem Statement
Invert a binary tree.
Testcase
Prerequisite Knowledge
Binary Tree
A binary tree is a tree data structure in which each parent node has a maximum of two child nodes.
Level Order Traversal
Level Order Tree Traversal is also known as Breadth-First Traversal. In this type of traversal, we traverse through and print the nodes at each level before traversing further down the tree, as shown in the example.
Problem Explanation
Inverting a Binary Tree
An inverted binary tree is a mirror image of the original binary tree. At every level of the binary tree, we must swap the left and right nodes in order to obtain an inverted image of the binary tree.
Algorithm
Recursive Approach
If the tree is empty, return NULL as the inverse of an empty tree is an empty tree.
Recursively traverse through the left and right branches of the tree in a depth-first manner.
When the leaf nodes have been reached, set the respective left and right pointers to NULL.
Backtrack through each level and swap the left and right sub-trees.
The process is completed when the root node is reached.
Code
Last updated
Was this helpful?