It's been a year since we last used the two tree, it's time to relive it.
"The definition of a binary tree"
A binary tree is a hierarchy, either an empty set or an element that becomes a root and two different sub-binary trees (recursive definitions, sub-binary trees may also be empty).
The two sub-binary trees are called Saozi right sub-tree respectively. The root node of the left subtree of a node is called the node's left child, and no child's point is called a leaf node.
Binary search tree is characterized by the value of nodes in the left subtree of each node being less than the value of that node, and the value of the node in the right subtree is greater than that point.
Here is the data structure I defined:
1 /**2 * Created by Tianhe on 2015/7/6.3 */4 //self-fulfilling binarytree5 Public classMybtree {6 PrivateObject element =NULL;7 PrivateMybtree left =NULL;8 PrivateMybtree right =NULL;9 Publicmybtree (Object o) {Tenelement =o; One } A Public voidsetElement (Object o) { -element =o; - } the Public voidsetleft (Mybtree o) { -left =o; - } - Public voidsetright (Mybtree o) { +right =o; - } +}
This sets the member variable to private and may affect subsequent use, but try it out first.
"Insert Element"
Algorithm: If the binary tree is empty, a root node is created with the new element, otherwise the parent node is found for the new element. If the value of the new element is less than the parent node's value, the node of the new element is set to the left child of the parent node, otherwise it is set to the right child.
Here I used the recursive way, the code is as follows:
1 Public classMain {2 Public Static voidMain (string[] args) {3Mybtree root =NULL;4root = Insertelement (50, root);5Root = Insertelement (30, root);6root = Insertelement (60, root);7Root = Insertelement (30, root);8 }9 StaticMybtree Insertelement (into, Mybtree t) {Ten if(T = =NULL) { Onet =NewMybtree (o); A } - Else { - //Locate The parent node, and insert the node by recursion theMybtree current =T; - while(Current! =NULL) { - if(O <current.getelement ()) { - insertelement (O, Current.getleft ()); + } - Else if(O >current.getelement ()) { + insertelement (O, Current.getright ()); A } at Else { -System.out.println ("There is already this element in your binary tree"); - Break; - } - } - } in returnT; - } to}
But after clicking on the run there was an embarrassing result-no execution. After debugging I found that because of the problem with the function call: Java is a value call, it means that I do not add to the function within the original instance of the node.
For this issue, I came up with several workarounds:
1.
"Java" binary tree (binary trees) revisited