1 minute read

For this problem I am given the root of a binary tree and I must return a fully inverted tree. URL: https://leetcode.com/problems/invert-binary-tree/

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 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) {
        if (root == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

Explanation:
Line 18 handles the case where the root is null (the tree has 0 nodes) and it is also the base case of the recursive algorithm.
Lines 21-23 swap the left and right pointer of the root.
Line 24 and 25 run the procedure recursively on the left and right child nodes. The return value is not needed for these calls.
Line 26 returns the root of the modified tree to the caller function.