
Problem (aka LeetCode 226)
Given the root of a binary tree, swap every node’s left and right children.
☕ Java Solution (Recursive)
class Solution { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } } public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode tmp = root.left; root.left = invertTree(root.right); root.right = invertTree(tmp); return root; } }public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
🧠 Complexity
▪️Time: O(n) — each node is visited once.
▪️Space: O(h) call stack (worst-case O(n), best-case O(log n) for balanced trees).
☝️ Takeaway
Inversion is a perfect warm-up: shows you understand tree traversal and swapping, and lets you discuss recursion vs. iteration, depth/width trade-offs, and worst-case stack/queue use.
#java #codinginterview #interviewprep #datastructures #binarytree #algorithms #leetcode #javaprogramming #recursion #bigO
Go further with Java certification:
Java👇
Spring👇
SpringBook👇