How do you invert a binary tree?
- User
How do you invert a binary tree?
- Assistant
Inverting a binary tree involves swapping every left child with its corresponding right child recursively. Here is a Python function that accomplishes this:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def invertBinaryTree(node): if node is None: return else: temp = node invertBinaryTree(node.left) invertBinaryTree(node.right) temp = node.left node.left = node.right node.right = tempThis function works by performing a depth-first search and swapping the left and right children of each node starting from the root. This effectively inverts the tree.
- User
can you show me the example code in ruby?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.