Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
class Node:
    def __init__(self,mark,left,right):
        self.mark = mark
        self.left = left
        self.right = right

def leaf(m):
    return Node(m,None,None)



def insert(tree:Node,item)->Node:
    if tree is None:
        return leaf(item)
    elif tree.mark > item:
        return Node(tree.mark,insert(tree.left,item),tree.right)
    elif tree.mark < item:
        return Node(tree.mark,tree.left,insert(tree.right,item))
    else:            ## i mean this line and the following line
        return tree     ##


What I have tried:

i inserted nodes to tree successfully but i dont know the need for return tree in the else statement ?
Posted
Updated 7-Sep-20 10:51am
v5

1 solution

Python
elif tree.mark > item:
    return Node(tree.mark,insert(tree.left,item),tree.right)
elif tree.mark < item:
    return Node(tree.mark,tree.left,insert(tree.right,item))
else:            ## i mean this line and the following line
    return tree     ##

The last line is to make sure if tree.mark == item then you don't do anything and return as is.

3 conditions:
- If item is greater then insert right
- If item is smaller then insert left
- if item is same then don't insert and return as is.

If you take sample example and try, it would help.
 
Share this answer
 
Comments
CPallini 8-Sep-20 2:27am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900