An exercise in the Binary search tree section of the algorithm: traversing a binary lookup tree by layer.
You can use queues to manage the nodes in the binary lookup tree, and the nodes are queued as follows:
- Node x enqueued
- Use the first element of a queue when the queue is not empty
- If the node first.left is not empty, fisrt.left the queue
- If the node first.right is not empty, first.right the queue
- Bring the first node out of the team
/*** Created by Elvalad on 2014/12/5. * Traverse binary search tree by layer*/ImportJava.util.Iterator;Importjava.util.LinkedList; Public classPrintbst<keyextendsComparable<key>, value> { PrivateNode Root;/*root node*/ Private intN/*Number of nodes*/ Private classNode {key key; /*Key*/Value Val; /*value*/Node left; /*left dial hand tree*/Node right; /*Right sub-tree*/Node (Key key, Value val) { This. Key =key; This. val =Val; } } Public voidput (key key, Value val) {root=put (Root, Key, Val); N++; } Privatenode put (node X, key key, Value val) {if(x = =NULL) { return NewNode (Key, Val); } intCMP =Key.compareto (X.key); if(CMP < 0) {X.left=put (X.left, Key, Val); } Else if(CMP > 0) {X.right=put (X.right, Key, Val); } Else{x.val=Val; } returnx; } Public intheight (Node x) {if(x = =NULL) return0; intLH =height (x.left); intRH =height (x.right); return(LH > RH)? (LH + 1): (RH + 1); } /*use queues to queue each node in a certain order, traversing the elements in the queue to*/ Public voidPrintbst (Node x) {if(x = =NULL) return; LinkedList<Node> Lln =NewLinkedlist<node>(); Lln.add (x); while(!Lln.isempty ()) {Node First=Lln.getfirst (); System.out.println (First.key); if(First.left! =NULL) {lln.add (first.left); } if(First.right! =NULL) {lln.add (first.right); } lln.remove (); } } Public Static voidMain (string[] args) {Printbst<string, integer> Pbst =NewPrintbst<string, integer>(); Pbst.put ("DDDD", 4); Pbst.put ("CCC", 3); Pbst.put ("A", 1); Pbst.put ("BB", 2); Pbst.put ("FFFFFF", 6); Pbst.put ("Eeeee", 5); Pbst.printbst (Pbst.root); }}
Traverse binary lookup Tree by layer