I looked into the code of inverting binary tree in the internet. But I couldnt what it is doing. Its written in Python. I am a python programmer myself but couldnt understand it.
The snippet is as follows:
def invertTree(root):
if root:
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
I don't understand this root.left
and root.right
. Root is the main node in the graph, it will be an integer or a single character. But what does root.left represent in Python? I honestly do not get it.
Update:
My understanding is the node is access like below:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def PrintTree(self):
print(self.data)
root = Node(10)
root.PrintTree()
A binary tree can be used to store elements sorted by a key.(Look for the balanced binary tree for more advanced topic.) If the elements are sorted in ascending order, for any subtree T with the root node R, any element in the left branch of R should be smaller than any element in the right branch of R.
This is a heavily modified version of the example code at Invert a Binary Tree by Shivali Bhadaniya.
'''
5 5
/ \ / \
/ \ / \
3 7 =======> 7 3
/ \ / \ / \
1 4 6 6 4 1
'''
class Node:
def __init__(self, data):
self.left = self.right = None
self.data = data
def __repr__(self):
return repr(self.data)
def invert(root):
left, right = root.left, root.right
print(['visiting', root, 'swapping', left, right])
root.left, root.right = right, left
if left: invert(left)
if right: invert(right)
root = Node(5)
root.left = node3 = Node(3)
root.right = node7 = Node(7)
node3.left = Node(1)
node3.right = Node(4)
node7.left = Node(6)
invert(root)
This will output the following.
['visiting', 5, 'swapping', 3, 7]
['visiting', 3, 'swapping', 1, 4]
['visiting', 1, 'swapping', None, None]
['visiting', 4, 'swapping', None, None]
['visiting', 7, 'swapping', 6, None]
['visiting', 6, 'swapping', None, None]
In the above example, the tree before calling invert()
was sorted in ascending order. After the call, it will be sorted in descending order. That's why the operation is called 'inversion'.
You can understand why the simple recursion of swaping the left child and the right child results in the inversion, by simulating the above example code with a pencil and paper manually. Compare logs with your calculation.