In the words of Wikipedia, a binary tree is a tree structure with up to two subtrees per node. But today we are talking about a two-fork search tree, which is an extension of the binary tree, and adds a few restrictions to the two-fork lookup tree.
Let's look at the binary search tree what is the nature of it, if the left dial hand tree is not empty, then must be all less than equal to the root node, the same right subtree is the same, and the subtree is two fork to find the tree. There are no nodes with the same key value in the last tree. If the above four properties of the two-fork tree is a binary search tree. Let's take a picture of a two-fork search tree, and now it's not all about the truth.
We still have to start from the beginning, because it is a binary tree is a data structure, then there must be a definition, we look at how it is defined, in fact, is the data, Zuozi, right sub-tree. It is a class, if you want to create a node root = node (8), like this you create a root node.
Class node: "" " two fork tree left and right" "" def __init__ (self, data): "" " Node Structure" "" self.left = None self.right = none self.data = Data
Now that the definition of the node is OK, let's take a look at the Insert function, insert. In fact, the insertion function is the idea of dichotomy, because the nature of binary search tree, we can use a two-point method to find the location of the insertion. There is also the meaning of recursion, the meaning is not to the leaf node has been looking down, find composite the value of its data into the corresponding node.
def insert (self, data): "" " Insert node data " "" if data < self.data: if Self.left is None: self.left = Node (data) else: self.left.insert (data) elif data > Self.data: if Self.right is None: Self.right = Node (data) else: self.right.insert (data)
We can continue to construct our little tree, and continue to insert several nodes to refine this little tree.
Root.insert (3) Root.insert (+) Root.insert (1)
We can simulate the insertion process ah, insert 3 o'clock and 8 compare less than 8 and 8 of the left node is empty, so inserted on the left node of 8. When inserting 10, it is inserted directly into the right node of 8, inserting 1 is less than 8 compared with 8, and 8 of the left subtree is not empty, recursive call 8 of the left subtree, and then 3 compared to 3 small and 3 of the left subtree is empty, inserted into the left node 3.
Root.insert (6) Root.insert (4) Root.insert (7) Root.insert (+) Root.insert (13)
Again to the point, the small partners should go to bed, then tomorrow to write a traverse god horse.
Python implementation of Binary tree lookup--(insert)