All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0226_invert_binary_tree.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0201_0300.s0226_invert_binary_tree;

// #Easy #Top_100_Liked_Questions #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
// #Data_Structure_I_Day_12_Tree #Level_2_Day_6_Tree #Udemy_Tree_Stack_Queue
// #Big_O_Time_O(n)_Space_O(n) #2022_07_04_Time_0_ms_(100.00%)_Space_42_MB_(20.73%)

import com_github_leetcode.TreeNode;

/*
 * 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;
 *     }
 * }
 */
/**
 * 226 - Invert Binary Tree\.
 *
 * Easy
 *
 * Given the `root` of a binary tree, invert the tree, and return _its root_.
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg)
 *
 * **Input:** root = [4,2,7,1,3,6,9]
 *
 * **Output:** [4,7,2,9,6,3,1] 
 *
 * **Example 2:**
 *
 * ![](https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg)
 *
 * **Input:** root = [2,1,3]
 *
 * **Output:** [2,3,1] 
 *
 * **Example 3:**
 *
 * **Input:** root = []
 *
 * **Output:** [] 
 *
 * **Constraints:**
 *
 * *   The number of nodes in the tree is in the range `[0, 100]`.
 * *   `-100 <= Node.val <= 100`
**/
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(temp);
        return root;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy