Wed. Jun 19th, 2024

# LeetCode – Tree – Invert Binary Tree

#### ByKnight Coderz

Apr 13, 2020

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);        }   }}``