226. Invert Binary Tree

1. Description

Invert a binary tree.

2. Solutions

Recursive

n is the number of nodes in root
Time complexity: O(n)
Space complexity: O(n)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root != nullptr) {
            root->left = invertTree(root->left);
            root->right = invertTree(root->right);
            swap(root->left, root->right);

            return root;
        } else {
            return nullptr;
        }

    }
};
Last updated:
Tags: Tree
comments powered by Disqus