⬅ Previous Topic
Find Diameter of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
⬅ Previous Topic
Find Diameter of a Binary Treeroot
node of the binary tree.null
, return.left
and right
children of the current node.left
subtree.right
subtree.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def mirror(root):
if root is None:
return
root.left, root.right = root.right, root.left
mirror(root.left)
mirror(root.right)
return root
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / / \
# 4 5 6
root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, TreeNode(5), TreeNode(6)))
mirror(root)
# The tree is now transformed into its mirror image
⬅ Previous Topic
Find Diameter of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.