226. Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
Thoughts
Seems like a pretty simple problem, I would imagine that doing this recursively would be the easiest way to go about it
- Simply swap the left and right nodes, then recursively swap the child node's left and right nodes
Solution
/**
* 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;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// Handle null case
if (root == null) return null;
// Recursively swap the left and right nodes
if (root.left != null && root.right != null) {
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
invertTree(root.left);
invertTree(root.right);
} else if (root.left == null) {
root.left = root.right;
root.right = null;
invertTree(root.left);
} else {
root.right = root.left;
root.left = null;
invertTree(root.right);
}
return root;
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Conclusion
Pretty simple algorithm to implement and understand, good refresher on tree stuff. My space complexity is O(n) and I feel like there is a more space efficient algorithm to complete the task. I will revisit this problem in the future and try to devise a better algorithm.