Invert Binary Tree
In this blog, we'll be solving the Invert Binary Tree problem on LeetCode.
Problem Overview
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
The Approach
You can check the video below for a detailed explanation of the approach:
Inverting binary trees means swapping the left and right nodes of each node in the tree. We can do this recursively by traversing the tree and swapping the left and right nodes of each node.
- Create a recursive function that takes in a node as an argument.
- If the node is null, return the node.
- Recursively call the function on the left and right nodes of the current node.
- Store the return value of the left and right node in a variable.
- Swap the left and right nodes of the current node.
- Return the current node.
The solution
1const traverse = node => {2 if (!node) return node34 const leftNode = traverse(node.left)5 const rightNode = traverse(node.right)67 node.left = rightNode8 node.right = leftNode910 return node11}1213var invertTree = function (root) {14 return traverse(root)15}
Complexity Analysis
- Time Complexity: O(n) - We traverse the entire tree once.
- Space Complexity: O(n) - The space occupied by the call stack is proportional to the height of the tree. In the worst case, the tree is linear, and the height is O(n).
Shameless Plug
I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
Contacts
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: