Sure, here's an expert-level technical interview question on inverting a binary tree:
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.
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
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;
}
invertTree
function takes a pointer to the root of the binary tree as input and returns a pointer to the inverted tree's root.invertTree
function, we recursively swap the left and right subtrees of each node in the binary tree by using a temporary pointer.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.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.