Below is a very nice implementation of binary search tree,the first couple of searches will yield lines of code similar to these sort. However I want to further reduces the number of lines of code.
class Node: def __init__(self,key): self.val = key self.left = None self.right = None def insert(root, node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node)
I want to write the final code much more succintly, is it possible:
def insert(root, node): if root is None: root = node return root if root.val < node.val: root.right = insert(root.right, node) elif root.val >= node.val: root.left = insert(root.left, node)
I have written bst in C++ long time ago, so I feel the insertion routine can be minimized. However, as it so happens, it does not give me the result as I expected.