Find the parent of a node in binary tree in Python
In this tutorial, you will learn how to find the parent of a node in a binary tree using Python Programming Language.
What is a Binary Tree?
A binary tree is a data structure in which each node has a maximum of two child nodes. A binary tree has the benefits of both linked lists and an ordered array. We can perform insert, deletion operations just as we can perform the same in a linked list.
The relevant properties that have to take into consideration are as follows:
- The left sub-tree node’s value should be lesser than the parent node value.
- The right sub-tree node’s value is greater than the parent node value.
- The properties hold true for each node in the left sub-tree and the right sub-tree.
For this tutorial and program that has been given below I’ve taken the binary tree structure given below:
1 / \ 3 5 / \ 4 6 / 7
From the above tree let us implement the code that is given below.
Program to find the parent node in a binary tree
# Python program to print the parent of given node in a binary tree # Creating the Node class class Node: # Constructor to create a new node def __init__(self, value): self.value= value self.left = None self.right = None # If target is present in tree, then prints the parent node def printParent(root, target): if root == None: return False if root.value == target: return True # If target is present in tree, then prints the parent node if (printParent(root.left, target) or printParent(root.right, target)): print (root.value) # Formation of the binary tree root = Node(1) root.left = Node(3) root.right = Node(5) root.right.left = Node(4) root.right.right = Node(6) root.right.right.left = Node(7) printParent(root, 7)
The above program implemented finds the parent node of the node”7″. And by looking at the tree given above, it obvious that the parent node is 6.
This how we find the parent of a node using Python Programming Language.
You may also read: