Binary sort tree is also called binary search tree. It is either an empty tree or a two-fork tree with the following properties:
1. If the left dial hand tree is not empty, then all nodes on the left subtree are smaller than the value of its root node;
2. If the right subtree is not empty, then all nodes on the right subtree are larger than the value of its root node;
3. The left and right tree is also a two-fork sorting tree.
The code for establishing and traversing binary sort trees is as follows:
1 classnode{2 Public intdata;3 PublicNode left;4 PublicNode right;5 PublicNode (intdata) {6 This. data =data;7 This. left =NULL;8 This. right =NULL;9 }Ten } One A Public classbinarytree{ - - PrivateNode Root; the PublicBinaryTree () { -Root =NULL; - } - + //inserts a date into the sort binary tree - Public voidInsertintdata) { +Node NewNode =NewNode (data); A if(Root = =NULL) atRoot =NewNode; - Else{ -Node current =Root; - Node parent; - while(true) {//find the insertion position -Parent =Current ; in if(data<current.data) { -Current =Current.left; to if(Current = =NULL){ +Parent.left =NewNode; - return; the } * } $ Else{Panax NotoginsengCurrent =Current.right; - if(Current = =NULL){ theParent.right =NewNode; + return; A } the } + } - } $ } $ //Enter values to build a binary tree - Public voidBuildtree (int[] data) { - for(inti=0; i<data.length; i++) { the Insert (Data[i]); - }Wuyi } the //recursive implementation of middle sequence traversal method - Public voidinorder (Node localroot) { Wu if(Localroot! =NULL) { - inorder (localroot.left); AboutSystem.out.print (localroot.data+ ""); $ inorder (localroot.right); - } - } - Public voidinorder () { A This. Inorder ( This. root); + } the //recursive implementation of first order traversal method - Public voidPreorder (Node localroot) { $ if(Localroot! =NULL) { theSystem.out.print (localroot.data+ ""); the preorder (localroot.left); the preorder (localroot.right); the } - } in Public voidpreorder () { the This. Preorder ( This. root); the } About //Afterrecursive implementation of sequential traversal method the Public voidpostorder (Node localroot) { the if(Localroot! =NULL) { the Postorder (localroot.left); + Postorder (localroot.right); -System.out.print (localroot.data+ ""); the }Bayi } the Public voidPostorder () { the This. Postorder ( This. root); - } - the}
Java Two fork sort tree