How to implement binary search tree in Python

Source: Internet
Author: User
The data structure of each node in the binary search tree is one parent node pointer, one left child pointer, and one child pointer, there is also our own data, because only two children are left and right, so it is called a binary tree. On this basis, the binary tree meets another condition: the left child of each node is not greater than the node & amp; the right child of each node is greater than the node. the data structure of each node in the binary search tree is one parent node pointer, one left child pointer, and one child pointer, there is also our own data, because only two children are left and right, so it is called a binary tree. On this basis, the binary tree meets another condition: the left child of each node is not greater than this node & the right child of each node is greater than this node.

Binary search tree

We already know two different methods for getting key-value pairs in a set. Recall how these sets implement ADT (abstract data type) MAP. We will discuss two adt map implementation methods: List-based binary lookup and hash tables. In this section, we will learn the binary search tree, which is another Map set of keys pointing to values. in this case, we do not need to consider the actual position of elements in the tree, however, it is more efficient to search using binary trees.

Search tree operations

Before studying this implementation method, let's review the interfaces provided by adt map. We will notice that this interface is very similar to the Python dictionary.

  1. Map () creates a new empty Map set.

  2. Put (key, val) adds a new key-value pair to Map. If the key is already in the Map, a new value is used to replace the old value.

  3. Get (key) provides a key to return the data stored in Map or None.

  4. Del uses the del map [key] statement to delete key-value pairs from Map.

  5. Len () returns the number of key-value pairs saved in Map.

  6. If the given key is in Map, use the key in map statement to return True.

Search tree implementation

A binary search tree. if the key values in the left subtree are smaller than the parent node, and the key values in the right subtree are greater than the attributes of the parent node, we call this tree a BST search tree. As described earlier, when we implement Map, the BST method will guide us to achieve this. Figure 1 shows the feature of the binary search tree. the displayed key is not associated with any value. Note that this attribute applies to each parent node and child node. All keys in the left subtree are smaller than those in the root node. all keys in the right subtree are greater than those in the root node.

class BinarySearchTree:  def init(self):    self.root = None    self.size = 0  def length(self):    return self.size  def len(self):    return self.size  def iter(self):    return self.root.iter()

The TreeNode class provides many auxiliary functions, making the BinarySearchTree class method easier to implement. As shown in Listing 2, the structure of a tree node is implemented by these auxiliary functions. As you can see, these helper functions can divide a node as the left or right child and the child node type based on their locations. The TreeNode class clearly tracks the attributes of each parent node. When we discuss the implementation of the delete operation, you will understand why this is important.

Another interesting thing about the TreeNode implementation in Listing 2 is that we use optional Python parameters. The optional parameters allow us to create a tree node in several different situations. sometimes we want to create a new tree node, even if we already have a parent node and a child node. Like existing parent and child nodes, we can use the parent node and child node as parameters. Sometimes we also create a tree containing key-value pairs. we will not pass any parameters of the parent node or child node. In this case, the default value of the optional parameter is used.

Listing 2


class TreeNode:  def init(self,key,val,left=None,right=None,                    parent=None):    self.key = key    self.payload = val    self.leftChild = left    self.rightChild = right    self.parent = parent  def hasLeftChild(self):    return self.leftChild  def hasRightChild(self):    return self.rightChild  def isLeftChild(self):    return self.parent and self.parent.leftChild == self  def isRightChild(self):    return self.parent and self.parent.rightChild == self  def isRoot(self):    return not self.parent  def isLeaf(self):    return not (self.rightChild or self.leftChild)  def hasAnyChildren(self):    return self.rightChild or self.leftChild  def hasBothChildren(self):    return self.rightChild and self.leftChild  def replaceNodeData(self,key,value,lc,rc):    self.key = key    self.payload = value    self.leftChild = lc    self.rightChild = rc    if self.hasLeftChild():      self.leftChild.parent = self    if self.hasRightChild():      self.rightChild.parent = self

Now we have the BinarySearchTree and TreeNode classes. it is time to write a put method so that we can build a binary search tree. The put method is a method of the BinarySearchTree class. This method checks whether the tree has roots. If not, we will create a new tree node and set it as the root of the tree. If there is already a root node, we will call it ourselves for recursion and use the auxiliary function _ put to search the tree according to the following algorithms:

Start from the root node of the tree and search for a binary tree to compare the new key value and the key value of the current node. if the new key value is smaller than the current node, search for the left subtree. If the new key is greater than the current node, search for the right subtree.

When the left (or right) subtree is not found, the position in the tree is to set the position of the new node.
Add a node to the tree, create a new TreeNode object, and insert this object into the previous node of this vertex.

Listing 3 shows the Python code for inserting a new node into the tree. Follow these steps to compile a recursive algorithm for the _ put function. Note: When a new subtree is inserted, the current node (CurrentNode) is passed as the parent node to the new subtree.

An important issue for executing inserts is that duplicate key values cannot be correctly processed, and our tree implements key value replication, it creates a new node with the same key value as the original node in the right subtree. The consequence is that new nodes will not be found during the search process. We use a better way to insert duplicate key values. the old values are replaced by the values associated with the new key. We will leave you with the repair of this error as an exercise.

Listing 3


def put(self,key,val):  if self.root:    self._put(key,val,self.root)  else:    self.root = TreeNode(key,val)  self.size = self.size + 1def _put(self,key,val,currentNode):  if key < currentNode.key:    if currentNode.hasLeftChild():        self._put(key,val,currentNode.leftChild)    else:        currentNode.leftChild = TreeNode(key,val,parent=currentNode)  else:    if currentNode.hasRightChild():        self._put(key,val,currentNode.rightChild)    else:        currentNode.rightChild = TreeNode(key,val,parent=currentNode)

With the implementation of the put method, we can easily use the setitem method to overload [] as operators to call the put method (see Listing 4 ). This allows us to write python statements like myZipTree ['pluth U'] = 55446, which looks like a Python Dictionary.

Listing 4


def setitem(self,k,v):  self.put(k,v)

Figure 2 illustrates the process of inserting a new node into a binary search tree. The gray node shows the order of traversing tree nodes during the insertion process.

def get(self,key):  if self.root:    res = self._get(key,self.root)    if res:        return res.payload    else:        return None  else:    return Nonedef _get(self,key,currentNode):  if not currentNode:    return None  elif currentNode.key == key:    return currentNode  elif key < currentNode.key:    return self._get(key,currentNode.leftChild)  else:    return self._get(key,currentNode.rightChild)def getitem(self,key):  return self.get(key)

With get, we can write a BinarySearchTree contains method to implement the operation. The contains method simply calls the get method. if it returns a value, True is returned, if it is None, False is returned. See Listing 6.

Listing 6


def contains(self,key):  if self._get(key,self.root):    return True  else:    return False

Let's review the ins overload operator, which allows us to write such a statement:


if 'Northfield' in myZipTree:  print("oom ya ya")

The above is the details about how Python implements the binary search tree. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.