Python implements Binary Search Tree instance code and python Binary Tree instance
This article focuses on the implementation of Binary Search Tree in python. The specific introduction and implementation are as follows.
1. Binary Search Tree definition:
When the left subtree is not empty, the node value of the Left subtree is smaller than the root node. If the right subtree is not empty, the node value of the right subtree is greater than the root node, left/right subtree is a binary search tree
2. the leftmost node of the binary search tree is the minimum value. To search for the minimum value, you only need to traverse the node of the Left subtree until it is empty. Similarly, the maximum end of the rightmost node is the maximum value, you only need to traverse the node of the right subtree until it is empty. The insertion, query, and deletion of the binary search tree are implemented recursively. When deleting a node, find the node S first. If no child left or right of the node is empty, in this case, instead of deleting the node S, you can find the next node in its right subtree, pay the value of the next node to S, and then delete the next node. If the Left or Right child of node S is empty, delete the node S directly.
3. python Implementation of the Binary Search Tree:
Class TreeNode: def _ init _ (self, val): self. val = val; self. left = None; self. right = None; def insert (root, val): if root is None: root = TreeNode (val); else: if val <root. val: root. left = insert (root. left, val); # recursively Insert the element elif val> root. val: root. right = insert (root. right, val); return root; def query (root, val): if root is None: return; if root. val is val: return 1; if root. val <val: return query (root. right, val); # recursively query else: return query (root. left, val); def findmin (root): if root. left: return findmin (root. left); else: return root; def delnum (root, val): if root is None: return; if val <root. val: return delnum (root. left, val); elif val> root. val: return delnum (root. right, val); else: # Delete the case where the left and right children are empty if (root. left and root. right): tmp = finmin (root. right); # Find the successor node root. val = tmp. val; root. right = delnum (root. right, val); # actually deleted is this successor node else: if root. left is None: root = root. right; elif root. right is None: root = root. left; return root; # test code root = TreeNode (3); root = insert (root, 2); root = insert (root, 1); root = insert (root, 4); # print query (root, 3); print query (root, 1); root = delnum (root, 1); print query (root, 1 );
Result:
1
None
>>>
Summary
The above is all about python's implementation of the Binary Search Tree instance code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!