Given a binary tree, invert the binary tree - Inverting a binary tree means that the resulting binary tree should be a mirror replica of the input binary tree.
We will be taking the help of a queue
data structure in order to solve this problem. A queue has following properties.
enque
)dequeue
)Also, A queue helps in implenting what is called a Breadth First Traversal
- Which is a way of traversing a tree/graph in a Breadth first manner. i.e. , We first explore the same level of the tree (or the same breadth) and then move into deeper levels of the tree.
Simply put: neighbours first, children next.
queue
that contains only the tree
value to start with (this is passed as an input parameter to the function).currentNode
).tree.left
to the right
subtree and tree.right
to the left
subtree. Essentially, we are trying to swap the left and right subtrees of the current node.O(N)
Time complexity, because we check each element atmost once.O(N)
Space complexity, because we can have a skewed tree. In average case it will be O(H) where H is the height of the tree.In the recursive approach, we try to swap the left
and the right
children as we traverse the tree top to down. Once we hit the base case, form there on the actuall swapping starts to happen.
!tree
- return. This will be the base case.left
subtree to the right
variable and right
subtree to the left
variabletree.left = right;
tree.right = left;
What is happening is essentially we are travelling to the end of the tree, essentially trying to swap the end values first.
Since the end values are swapped by now, we move one level up (because of recursion, the function calls starts to pop off from the stack) and that is how the parents are swapped
O(N)
Time complexity, because we check each element atmost once.O(N)
Space complexity, because we can have a skewed tree. In average case it will be O(H) where H is the height of the tree.As we saw earlier in the recursive approach, we essentially swapped children nodes of a parent node but we did it for the leaf nodes first. In this approach, we are going to start with the root node, and keep on swapping as and when we encounter left and right subtrees.
!tree
- return. This will be our base case.tree.left
and tree.right
values. (We are going to use a swap helper method here). Essentially, we are performing the swap as the first thing in the function.O(N)
Time complexity, because we check each element atmost once.O(N)
Space complexity, because we can have a skewed tree. In average case it will be O(H) where H is the height of the tree.