Describe
Construction of binary tree, insertion of new nodes, first and second order of trees, and sequence of four traversal
Code
Importjava.util.LinkedList;ImportJava.util.Queue;classnode{ Public intdata; PublicNode left; PublicNode right; PublicNode (intdata) { This. data=data; This. left=NULL; This. right=NULL; }} Public classBinaryTree {PrivateNode Root; PublicBinaryTree () {root=NULL; } /** Insert to sort binary tree **/ Public voidInsertintdata) {Node NewNode=NewNode (data); if(root==NULL) {root=NewNode; return; } node Node=Root; Node parent; while(true) {Parent=node; if(data<node.data) {Node=Node.left; if(node==NULL) {Parent.left=NewNode; return; } }Else{node=Node.right; if(node==NULL) {Parent.right=NewNode; return; } } } } /** Build binary tree with numeric input **/ Public voidBuildtree (int[] data) { for(inti=0;i<data.length;i++) {Insert (data[i]); } } /** First Order traversal **/ Public voidPreorder () {preorder (root); } Public voidPreorder (node node) {if(node==NULL)return; System.out.print (Node.data+" "); Preorder (Node.left); Preorder (node.right); } /** Middle Sequence traversal **/ Public voidinorder () {inorder (root); } Public voidinorder (node node) {if(node==NULL)return; Preorder (Node.left); System.out.print (Node.data+" "); Preorder (node.right); } /** Post-post traversal **/ Public voidPostorder () {postorder (root); } Public voidPostorder (node node) {if(node==NULL)return; Preorder (Node.left); Preorder (node.right); System.out.print (Node.data+" "); } /** Sequence Traversal **/ Public voidLayertranverse () {node node=Root; Queue<Node> queque=NewLinkedlist<node>(); Queque.add (root); while(!Queque.isempty ()) {Node=Queque.poll (); System.out.print (Node.data+" "); if(node.left!=NULL) Queque.add (node.left); if(node.right!=NULL) Queque.add (node.right); } } Public Static voidMain (string[] args) {BinaryTree bitree=NewBinaryTree (); int[] data={2,8,7,4,9,3,1,6,7,5}; Bitree.buildtree (data); System.out.print ("Binary Tree First Order traversal:"); Bitree.preorder (); System.out.println (); System.out.print ("Binary tree in the middle sequence traversal:"); Bitree.inorder (); System.out.println (); System.out.print ("Binary tree after the post-traversal:"); Bitree.postorder (); System.out.println (); System.out.print ("Sequence traversal of a binary tree:"); Bitree.layertranverse (); System.out.println (); }}
Basic operation of Sort binary tree