226. Invert Binary Tree
Question:
Given the root of a binary tree, invert the tree, and return its root.
Example:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Input: root = [2,1,3]
Output: [2,3,1]
Input:
root = []Output: [] Constraints:
Source code
Version 1
Idea:
It is a recursive method and likes DFS traversal of the tree. Implement swap() method between left node and right node.
Time complexity: O(n)
Space complexity: O(h) P.S. h is the height of the tree for the call stack
1 | /** |
Version 2
Idea:
The other way is Stack and similars to BFS traversal of the tree.
Time complexity: O(n)
Space complexity: O(n)
1 | /** |