226. Invert Binary Tree
Last updated
Was this helpful?
Last updated
Was this helpful?
Invert a binary tree.
GeeksforGeeks
ProgramCreek
YouTube
Input: [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* Time complexity : O(n), where nn is the number of nodes in the tree.
* We cannot do better than that, since at the very least we have to
* visit each node to invert it.
* Space complexity : Because of recursion, O(h) function calls will be
* placed on the stack in the worst case, where hh is the height of
* the tree. Because h ∈ O(n), the space complexity is O(n).
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode tmpNode = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmpNode);
return root;
}
}
/**
* Time complexity : O(n), where n is the number of nodes in the tree.
* Space complexity : O(n), since in the worst case, the queue will contain
* all nodes in one level of the binary tree. For a full binary tree,
* the leaf level has n/2 = O(n) leaves.
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode currNode = queue.poll();
TreeNode tmpNode = currNode.left;
currNode.left = currNode.right;
currNode.right = tmpNode;
if(currNode.left != null) queue.add(currNode.left);
if(currNode.right != null) queue.add(currNode.right);
}
return root;
}
}