Find Parent of a Node in Binary Tree | Python Code

Find Parent of a Node in Binary Tree | Python Code

Problem statement:

Write a program to find the parent of the node in binary tree (BT).

(This question is asked in many coding interview rounds.)

Example:

binary tree

Let’s take the example of the above binary tree.

The parent of node 3 is 1.
The parent of node 5 is 4.
The parent of node 6 is 5.

You can solve this in any programming language like C/C++, Java or Python.

Here I’m writing a Python program to find the parent of the given node in a binary tree.

Python Solution

Before we find parent of a node in binary tree, we have to create the binary tree using Python. And it is simple.

Prerequiste:

To find the parent of the given node in BT, we are using recursion.

Python code:

class node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

root = node(4, node(1, node(7), node(3)), node(5,None,node(6)))

def parent(obj, val):
    if obj:
        if (obj.left and obj.left.val==val) or (obj.right and obj.right.val==val):
            return obj.val or parent(obj.left, val) or parent(obj.right, val)
        else:
            return parent(obj.left, val) or parent(obj.right, val)


print(f"The parent of node 3 is {parent(root, 3)}.")

Output:

The parent of node 3 is 1.

With little modification, you can also print and find all the ancestors of the given node in the binary tree.

If you have any questions or doubts, feel free to put that in the comment section below. You can also provide an alternate solution to the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *