LeetCode - Tree - Invert Binary Tree

Invert a binary tree.

Example:

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(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        TreeNode node = root;
        getInvertedNode(node);
        return node;
    }
    
    public void getInvertedNode(TreeNode node) {
        if(node != null){
            if(node.left != null || node.right != null){
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
            }
            
            TreeNode left = node.left;
            TreeNode right = node.right;
            if(left != null) getInvertedNode(left);
            if(right != null) getInvertedNode(right);
        }
   }
}

Recent Updates

Recent updates on DevOpsPal

Social

Follow us of social for latest updates.

DevOps Hub

Links to get started.