Analysis
The structure of the binary tree: root node, Zuozi, right sub-tree. Where the value of Zuozi must be small for the root node, the value of the right subtree must be greater than the Roots node. Constructing this tree structure is to create a class and provide a method that automatically creates nodes and automatically hangs to the appropriate location of a two-fork tree when given a value.
Traversal of binary tree: It is divided into first order traversal, middle sequence traversal and post-order traversal. First Order traversal: root, left, and right.
Traversing in: Left, Root, right.
Subsequent traversal: Left, right, root.
Binary Tree application: Encryption and decryption, file compression, fast query, fast traversal and so on.
1, constructs the node object of the two fork tree, and provides the inserting method.
1 Private intData//Storing node Data2 PrivateBinaryTree left;//left dial hand tree3 PrivateBinaryTree right;//Right sub-tree4 5 /**6 * Construct method, create new node7 */8 PublicBinaryTree (intdata) {9 This. data =data;Ten This. left =NULL; One This. right =NULL; A } - - /** the * Insert new node - */ - Public voidInsert (BinaryTree root,intdata) { - if(Root! =NULL){ + if(Data <root.data) { - if(Root.left = =NULL){//left dial hand tree vacancy, inserting +Root.left =NewBinaryTree (data); A}Else{//left dial hand tree is not empty, recursive left subtree as root node at Insert (root.left, data); - } -}Else{ - if(Root.right = =NULL){ -Root.right =NewBinaryTree (data); -}Else{ in Insert (root.right, data); - } to } + } - } the
2. The insertion node constructs a two-fork tree and traverses the two-fork tree through the sequence traversal, the middle sequence traversal, and the post-order traversal
1 Public Static voidMain (string[] args) {2BinaryTree root =NewBinaryTree (6);//Creating the root node3 int[] A = {2,1,4,5,3,8,6,7,9};4 for(inti = 0; i < a.length; i++) {//inserting Nodes5 Root.insert (Root, A[i]);6 }7 8 pretraversal (root);9 midtraversal (root);Ten suftraversal (root); One}
1 //First Order Traversal2 Public Static voidpretraversal (BinaryTree root) {3 if(Root! =NULL) {4System.out.print (Root.getdata () + "-");5 pretraversal (Root.getleft ());6 pretraversal (Root.getright ());7 }8 9 }Ten One //Middle Sequence Traversal A Public Static voidmidtraversal (BinaryTree root) { - if(Root! =NULL){ - midtraversal (Root.getleft ()); theSystem.out.print (Root.getdata () + "-"); - midtraversal (Root.getright ()); - } - } + - //Post-post traversal + Public Static voidsuftraversal (BinaryTree root) { A if(Root! =NULL){ at suftraversal (Root.getleft ()); - suftraversal (Root.getright ()); -System.out.print (Root.getdata () + "-"); - } -}
Java constructs and traverses binary trees