How do you invert a binary tree?
- User
How do you invert a binary tree?
Assistant
Here is how you invert or mirror a binary tree:
-
Recursively invert the left and right subtrees first. So invert the left subtree and invert the right subtree.
-
Then swap the left and right pointers of the current node.
So the pseudocode is:
invert(node): if node is null return temp = node.left node.left = invert(node.right) node.right = invert(temp) return nodeTo explain further - we want to swap the left and right subtree of every node. But we do so recursively, by inverting the left and right subtrees first before swapping the pointer. This allows us to invert the tree recursively and in place without needing any external storage.
The key things to remember are:
- Invert the left and right subtrees recursively first
- Then swap the left and right pointers of the current node
This allows us to invert the whole tree recursively.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.