InvertBinaryTree Code : Python
ฝัง
- เผยแพร่เมื่อ 24 ก.ย. 2024
- InvertBinaryTree Python code explained
class Node:
def __init__(self, value):
Initialize the node with a value, and left and right children as None
self.value = value
self.left = None
self.right = None
Function to invert the binary tree recursively
def invert_tree(node):
if node is None:
return
Swap the left and right children
temp = node.left
node.left = node.right
node.right = temp
Recursively invert the left and right subtrees
invert_tree(node.left)
invert_tree(node.right)
Function to print the binary tree in in-order traversal
def print_in_inorder(node):
if node is None:
return
Recursively print the left subtree
print_in_inorder(node.left)
Print the current node's value
print(node.value)
Recursively print the right subtree
print_in_inorder(node.right)
Creating the binary tree
root = Node(8)
root.left = Node(7)
root.right = Node(4)
root.left.left = Node(3)
root.left.right = Node(6)
root.right.left = Node(7)
root.right.right = Node(9)
root.left.left.right = Node(6)
Print the original tree (in-order traversal)
print("Original Tree (In-order):")
print_in_inorder(root)
Invert the tree
invert_tree(root)
Print the tree after inversion (in-order traversal)
print("-----")
print("Inverted Tree (In-order):")
print_in_inorder(root)
Key Highlights:
invert_tree(): This function recursively inverts the binary tree by swapping the left and right children of each node.
print_in_inorder(): This function recursively prints the values of the binary tree in in-order traversal (left subtree → node → right subtree).
Flow:
The original tree is printed in in-order traversal.
The tree is inverted recursively.
The inverted tree is printed again in in-order traversal.
This will demonstrate the effect of inverting the binary tree.