Hyoseo Lee
01 Index 02 Current page Writing 03 Work 04 Notes 05 Games 06 Author
leetcode

226. Invert Binary Tree

Topic Depth-First Search
Area Data Structures
Summary
using recursion to solve this. flip the left and flip the right and switch left and right. that's all.

Problem

View on LeetCode →

Difficulty: Easy
Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree

Intuition

it seemed easy, and it was easy.

Approach

using recursion to solve this. flip the left and flip the right and switch left and right. that’s all.

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    if(!root){return NULL;}
    invertTree(root->left);
    invertTree(root->right);
    struct TreeNode* tmp;
    tmp = root->left;
    root->left = root->right;
    root->right = tmp;
    return root;
}

Complexity

  • Time: O(n)O(n)

  • Space: O(n)O(n)