Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to create balanced binary Tree by python

Shulou Source: shulou.com Published: 2022-05-31 10:40:49 09月30日 Update

This article introduces the knowledge of "how to create a balanced binary tree in python". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. The core of generating balanced tree is partial_tree method.

It takes a sequence and a number as parameters and returns a sequence recursively. The first is a structural tree, and the second is an element that is not included in the book.

2. The overall idea of the implementation is that each incoming sequence is divided into the left part, the vertex and the right part, until it can not be further split, and then returned layer by layer, and finally combined into a balanced binary tree.

Example

List_to_tree method converts ordered list into balanced binary tree A binary tree is divided into tree vertex, left subtree and right subtree, in which the value of the left subtree is smaller than that of the top node. The value of the right subtree is larger than the vertex of the tree. "" def make_tree (entry, left, right): # the method of creating a tree return (entry, left) Right) def entry (tree): # get the vertices of the tree return tree [0] def left_branch (tree): # get the left subtree return tree [1] def right_branch (tree): # get the right subtree return tree [2] def list_to_tree (elements): return partial_tree (elements, len (elements)) [0] def partial_tree (elts, n): if n = 0: return (() Elts) else: left_size = (n-1) 2 left_result = partial_tree (elts, left_size) left_tree = left_result [0] non_left_elts = left_result [1] right_size = n-(left_size + 1) this_entry = non_left_elts [0] right_result = partial_tree (non_left_ arts [1:] Right_size) right_tree = right_result [0] remaing_elts = right_result [1] # print ("entry", this_entry) # print ("left_tree", left_tree) # print ("right_tree", right_tree) return (make_tree (this_entry, left_tree, right_tree) Remaing_elts) if _ _ name__ = = "_ main__": tree = list_to_tree ((1,3,5,7,9)) print ("the generated balanced binary tree is:", tree) print ("vertices of the tree:", entry (tree)) print ("left subtree:", left_branch (tree)) print ("right subtree:" Right_branch (tree)) "how to create a balanced binary tree by python" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Subtree vertex sequence method content more knowledge generation practical orderly successful learning next center left element half parameter dilemma example practice train of thought Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Tech Info Redmi Microsoft Shulou Technology