Java recursive method to build search binary tree, with find keyword, insert new node function

Source: Internet
Author: User

Definition of binary sort tree:

The binary sort tree satisfies the following three properties (BST properties):

<1> if its left subtree is not empty, the values of all nodes on the left subtree are small values of the root node

<2> if its right subtree is not empty, the values of all nodes on the right subtree are greater than the value of the root node

<3> left, right subtree itself is a binary sort tree

According to the BST nature of the binary sort tree, it can be said that the value (or keyword) on each node of the binary sort tree is unique, and the result of the binary sort tree traversing the output in the middle sequence is necessarily an ordered increment sequence.

As shown in the following:

The recursive method is used to establish a two-fork sorting tree, which reduces the complicated comparison procedure and is more efficient. Only need to know the value of each node, according to the recursive method, first get the value of the first node, and then get the value of the second node, the second node and the first node to compare, if less than the value of the second node in the left subtree, if greater than, the value of the second node is placed in the right subtree, and gradually, Recursively sets the value of each node and eventually builds a complete two-fork sort tree.

When a binary sort tree lookup operation is performed, the value to be found is passed, compared to the root node, and, if not equal to the root node, recursively traverses the left subtree or the right subtree, depending on the value of the lookup and the size of the root node. Until the lookup value is found, the result is output.

When a binary sort tree is inserted, the value directly to be inserted is stored in an array using the ArrayList linked list, iterating through the array, passing in the new node value, and continuing to call the recursive method to establish the binary sort tree. The final result is a middle order traversal of the binary tree output.

The code is as follows:

 Packagetwo fork sorting tree;Importjava.util.ArrayList;ImportJava.util.Scanner; Public classSorttree {/**     * @authorLiu Yanbing * @date 2015-02-09 18:32*/        /** have built search binary tree, find keywords, and insert new node function * * Key: keyword, here can be as the value of the node * L: Left dial hand tree * r: Right subtree*/     Public intkey;  PublicSorttree L;  PublicSorttree R; /** Recursive method to build a binary sort tree*/     Public voidBulittree (intkey) {        //The newly added node is compared with the value of the root node, and the small root node is placed in the left subtree, which is greater than the root node in the right sub-tree        if(key< This. Key) {                                    if( This. l==NULL){                                     This. l=NewSorttree ();  This. l.key=key; }            Else                //Zuozi set up two fork trees recursively                 This. L.bulittree (key); }        Else if(key> This. Key) {            if( This. r==NULL){                 This. r=NewSorttree ();  This. r.key=key; }            Else                //right subtree recursively builds two fork tree                 This. R.bulittree (key); }    }        /** Recursive search keyword, if there is a keyword return message*/     Public voidSeach (intkey) {        //compared to the root node first, if not equal to the root node, according to the value of the lookup and the root node size, recursively traverse the left subtree or the right sub-tree        if(key== This. Key) System.out.println ("Get Current Value:" + This. Key); Else if(key< This. Key) This. L.seach (key); Else             This. R.seach (key); }         Public voidinorder () {if( This. l!=NULL) L.inorder (); System.out.print ( This. key+ ","); if( This. r!=NULL) R.inorder (); }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("Input node, the first input as the root node of the binary tree (input-1 end input):"); Scanner SC=NewScanner (system.in); ArrayList<integer>list=NewArraylist<integer>(); intn=Sc.nextint ();  while(N!=-1) {list.add (n); N=Sc.nextint (); }        int[]data=New int[(List.size ())];  for(intI=0;i<list.size (); i++) {Data[i]=List.get (i); } Sorttree St=NewSorttree (); St.key=data[0];  for(inti=1;i<data.length;i++) {st.bulittree (data[i]); } System.out.println (The search binary tree is created as follows (in the middle order traversal output): ");        St.inorder ();        System.out.println (); System.out.println ("Enter the action you want to take:"); System.out.println ("1. Find Current Value"); System.out.println ("2. Insert a new node"); intChoice=Sc.nextint (); Switch(choice) { Case1: {System.out.println ("Enter the value you want to find:"); intk=Sc.nextint ();            St.seach (k);  Break; }         Case2: {System.out.println ("Please enter a value for the new node (input-1 end input):"); intm=Sc.nextint ();  while(M!=-1) {List.add (M); M=Sc.nextint (); }             for(intI=data.length-1;i<list.size (); i++) {St.bulittree (List.get (i)); } System.out.println ("After inserting a new node, the results of the binary search tree are as follows (traversing the output in the middle order):");            St.inorder ();  Break; }        default: {System.out.println ("wrong input");} }    }    }

The debug results are as follows:

Java recursive method to build search binary tree, with find keyword, insert new node function

Related Article

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.