Implement binary search tree using Scheme)

Source: Internet
Author: User

I was surprised when I used scheme to finish this little exercise and looked at the written code. The program is very short. The code that defines the data structure, creates a binary tree, and traverses in the middle order adds up to more than 30 lines! Next I will talk about my thinking process step by step.

The objective is to build a binary search tree from a table, traverse it in the middle order, and store the traversal sequence in a table. To achieve this goal, we should first find out the question: what is a binary tree? Hmm ...... It is a data structure consisting of the root of the tree, the left subtree, And the right subtree. The left and right subtree are also Binary Trees. Well, considering that the only data structure in scheme is a table (list), the binary tree can be defined:
(List root left-branch right-Branch)

Next, we can implement the make-tree function, which combines the three parts of the binary tree into a binary tree:
(Define (make-tree root left-branch right-Branch)
(List root left-branch right-branch ))

In fact, make-tree is the meaning of list. Why? The first is to facilitate reading. The other reason is that this is a "encapsulation" function. If the data structure is changed in the future, it will not cause a severe "code earthquake ".

The structure of the tree has been defined. Naturally, the next step is to think about how to separate each part from such a data structure. I have implemented three functions: Root, left-branch, and right-branch. They all follow a parameter to represent a tree and return the root, left, and right subtree respectively. As defined above, the root of a tree is the first element in the table.
(Define (root tree)
(Car tree ))
The left subtree ranks second, that is, (CAR (CDR tree). Because the car And CDR are frequently used in scheme, adjacent ones can be merged and written as CADR. Therefore
(Define (left-branch tree)
(CADR tree ))
Similarly, you can write right-branch:
(Define (right-branch tree)
(Caddr tree ))

Another problem is how the empty tree is represented. I want to use an empty table "()" to represent the empty tree. In this way, you can write a function to judge whether a tree is empty:
(Define (empty-tree? Tree)
(Null? Tree ))

Well, these are our basic tools. Very simple, isn't it? You will be surprised later.

To build a binary tree, consider the simplest scenario: empty tree and tree with only one node. The empty tree is '(); I define a tree with only one node as a binary tree with empty left and right Subtrees. I use make-node to implement it. It takes a number as the parameter, and the result is a binary tree with null left and right subtree with that number as the root:
(Define (make-node num)
(Make-tree num '()'()))

It looks very intuitive. Next, we should consider how to build a binary search tree. I defined it as follows: a binary search tree is a non-empty node in the tree. Its left subnode value is smaller than its value or is empty, the value of the right subnode is greater than or equal to its value or is null. The binary search tree can be constructed using a node insertion method. It is not difficult to obtain such a recursive algorithm:

  • If the tree to be inserted is empty, the result is the node. otherwise:

    • If the value of the node to be inserted is smaller than the value of the root node, the left subtree is inserted;
    • If the value of the node to be inserted is greater than or equal to the value of the root node, the right subtree is inserted.

The Code is as follows. The meaning of (insert-num tree num) is to insert a number num into the binary search tree, and the result is still a binary search tree:
(Define (insert-num tree num)
(If (empty-tree? Tree)
(Make-node num)
(Cond (<num (root tree ))
(Make-tree (root tree)
(Insert-num (left-branch tree) num)
(Right-branch tree )))
(> = Num (root tree ))
(Make-tree (root tree)
(Left-branch tree)
(Insert-num (right-branch tree) num ))))))

Let's take a look at the goal: to build a binary search tree from a table. Now we can build Binary Trees one by one. How can we deal with a bunch of them all at once? I want the function of building a tree to be used like this: (build-tree (list ....)). Hmm ...... If the table is empty, the result is an empty tree. Otherwise, assume that the table contains n elements, and the last n-1 elements constitute a binary search tree, the first element is inserted into the tree. Isn't this a recursive algorithm? Then I heard a slight keyboard noise:
(Define (build-tree items)
(If (null? Items)
'()
(Insert-num (build-tree (CDR items ))))

Be careful, and you will find that this method is inserted into the binary tree from the back to the back. Now, we can try:
(Define T1 (build-tree (List 1 2 4-1 )))
(Define T2 (build-tree (List 1 3 9 21 )))
T1
T2
Result:
(-1 () (4 (2 (1 ()())())()))
(21 (9 (3 (1 ()())())())())

It looks good. You can try again. It should be okay. Let's take a look at how far it is from the target ...... Ha! The difference is that the traversal sequence is saved in a table by performing a middle-order traversal. You can use this method to traverse in the middle order. However, the result is saved in a table. This is not difficult. In scheme, the table has an append operation. It can merge any number of tables into one table, and the table sequence remains unchanged. In this way, you can use append to generate this table: "traversing the table obtained from the left subtree + root node + traversing the table obtained from the right subtree" is the final goal!

(Define (mid-order-Traverse tree)
(If (empty-tree? Tree)
'()
(Append (mid-order-Traverse (left-branch tree ))
(List (root tree ))
(Mid-order-Traverse (right-branch tree )))))

Try it:
(Mid-order-Traverse T1)
(Mid-order-Traverse T2)
The result is:
(-1 1 2 4)
(1 3 9 21)

Success!

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.