11. Invert Binary Tree

Link to the problem

Description

Invert a binary tree.

Example

Input: [4,2,7,1,3,6,9], Output: [4, 7, 2, 9, 6, 3, 1]

Idea

Recursively invert the left and right tree, rewire them to the root.

Solution

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

68 / 68 test cases passed.
Runtime: 0 ms

你可能感兴趣的:(11. Invert Binary Tree)