Tree insertion and variable referencing - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Tree insertion and variable referencing (/thread-6828.html) |
Tree insertion and variable referencing - hshivaraj - Dec-09-2017 Hey all! This is probably very basic for some people , but i really cant get my head around this. The code below performs binary tree insertion. The thing i cant understand is, you'll notice in the _insert function return root. I really dont see the point of that return. However with out that return root. The tree doesn't parse. But however in the calling function insert i dont assign that returned value from _insert to anything. Yet its required. Please help me understand this? def insert(self, val): if self.root is None: self.root = Node(val) else: self._insert(self.root, val) def _insert(self, root, val): print(id(root)) if root is None: return Node(val) if val <= root.val: root.left = self._insert(root.left, val) else: root.right = self._insert(root.right, val) return root RE: Tree insertion and variable referencing - Windspar - Dec-09-2017 because it recursive function. root.left and root.right need a node. root.left = self._insert(root.left, val) # need the return I believe it to be. None is not a reference variable. you could also do this. class Root: def __init__(self): self.root = None def insert(self, val, root='self'): if root == 'self': self.root = self.insert(val, self.root) elif root is None: return Node(val) elif val <= root.value: root.left = self.insert(val, root.left) else: root.right = self.insert(val, root.right) return root RE: Tree insertion and variable referencing - hshivaraj - Dec-10-2017 def insert(self, val, root='self'):[b][/b] Clever - I didn't know you can do that. Assign self as default argument as a string.
RE: Tree insertion and variable referencing - Windspar - Dec-10-2017 'self' is just a string. This just check it. def insert(self, val, root='self'): if root == 'self': self.root = self.insert(val, self.root)As long as root is not None or a Node. You can have it be anything else. def insert(self, val, root=True): if root is True: self.root = self.insert(val, self.root) |