Menu

Project Gimu

Software research and development

Inverting a Binary Tree

Input tree

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Result tree

     4
   /   \
  7     2
 / \   / \
9   6 3   1

The binary tree:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

Solution

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

Leave a Reply