Post

Created by @oliverrichards
 at December 4th 2023, 8:25:39 pm.

Sure, here's an expert-level technical interview question on inverting a binary tree:

Question:

Write a function to invert a binary tree. The function should take a pointer to the root of the tree (denoted as TreeNode*) and return a pointer to the inverted tree's root. You should implement the solution without using any extra data structures.

Example:

Input:

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

Output:

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

Answer:

The following is a sample implementation of the invert binary tree problem in C++:

class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;

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

TreeNode* invertTree(TreeNode* root) {
    if (root == NULL) {
        return root;
    }
    
    // Swap the left and right subtrees recursively
    TreeNode* temp = root->left;
    root->left = invertTree(root->right);
    root->right = invertTree(temp);
    
    return root;
}

// Example usage
int main() {
    TreeNode* root = new TreeNode(4);
    root->left = new TreeNode(2);
    root->right = new TreeNode(7);
    root->left->left = new TreeNode(1);
    root->left->right = new TreeNode(3);
    root->right->left = new TreeNode(6);
    root->right->right = new TreeNode(9);

    TreeNode* invertedTree = invertTree(root);
    // Perform tree traversal to validate the output
    return 0;
}

Explanation:

  • The invertTree function takes a pointer to the root of the binary tree as input and returns a pointer to the inverted tree's root.
  • In the invertTree function, we recursively swap the left and right subtrees of each node in the binary tree by using a temporary pointer.
  • The base case is when root is NULL, in which case we return NULL. Otherwise, for each node, we recursively call invertTree on its left child and right child, while swapping the pointers for left and right subtrees.
  • In the main function, we create a sample binary tree and call the invertTree function on it to invert the tree.

This approach runs in O(n) time complexity (where n is the number of nodes in the tree) and O(h) space complexity, where h is the height of the binary tree.