Binary tree chain storage and traversal

Source: Internet
Author: User

12 chain storage of the cross-tree1.1 Chain-store

Sequential storage is less efficient for space utilization, so the binary tree generally uses a chain-based storage structure and a linked list to store a binary tree. a two-fork list contains at least 3 domains: data field , left pointer field lchild , and right pointer field rchild, If you add a pointer to a parent node , it becomes a three-pronged list .

The chain-store structure of the binary tree is as follows:

/**@author*/privateclass  node{    Integer data;    Node lchild, Rchild;}

create a two-fork tree recursively based on the complete binary tree sequence, and the nonexistent nodes in the input sequence are replaced with 0, and the following are the code created and some useful methods.

/*** Store First-order input two-fork tree, default size is 10, when more than 10 automatically call resize method expansion*/PrivateInteger[] Nodes =NewInteger[10]; PublicLinkbitree () {init ();}/*** Get root node *@return */ PublicNode Getroot () {returnRoot;}/*** Full of automatic expansion *@paramMax*/Private voidResizeintmax) {integer[] Temp=NewInteger[max];  for(inti=0; i<nodes.length; i++) {Temp[i]=Nodes[i]; } nodes=temp;}/*** First Order Input binary tree, non-existent node use 0*/ Public voidinit () {System.out.println ("First sequence input a binary tree, non-existent nodes are replaced with 0, separated by commas:");//string[] ins = stdin.readstring (). Split (",");string[] ins = "1,2,3,4,0,5,7,8". Split (","); N=ins.length;  for(inti = 0; i < ins.length; i++) {        if(i>=nodes.length) {Resize (2 * nodes.length);//twice times the expansion} Nodes[i]=integer.valueof (Ins[i]); } System.out.println ("Linkbitree [nodes=" + arrays.tostring (nodes) + "]"); Root= Build (1);//Recursive tree creationSYSTEM.OUT.PRINTLN ("The Input tree height is:" +depth (root)); Print ();}/*** Recursive creation of a tree using a complete binary tree sequence *@paramnode *@paramData*/ PublicNode Build (intindex) {    if(Index >N) {return NULL; } Integer tmp= Nodes[index-1];//gets the value of the node.    if(TMP = = 0) {//0 indicates that the node does not exist.        return NULL; } Else{node node=NewNode (); Node.data=tmp; Node.lchild= Build (2 * index);//Create a left sub-treeNode.rchild = Build (2 * index + 1);//Create right subtree        returnnode; }}/*** Recursion Gets the height of the binary tree *@return */ Public intDepth (node node) {if(Node! =NULL){        intL = Depth (node.lchild);//Zuozi Height        intr = Depth (Node.rchild);//Right Sub-tree height        returnL > R? L + 1:r + 1;//the height of the tree is the maximum height of the subtree plus the root node    }    return0;//Empty tree height is 0}
1.2 Hierarchy Traversal
/*** Hierarchical traversal, using queues is implemented*/ Public voidLevelorder (Node root) {Ringbuffer<Node> queue =NewRingbuffer<node> (n+1); Queue.put (root); //root node Advanced queue         while(Queue.size () >0) {Node tmp=Queue.get (); System.out.print (Tmp.data+ " ");//Root        if(Tmp.lchild! =NULL) {//if the left subtree of the root node is present, the left subtree is numbered into the stackQueue.put (Tmp.lchild); }                if(Tmp.rchild! =NULL) {//if the right subtree of the root node is present, the right subtree is numbered into the stackQueue.put (Tmp.rchild); }    }}
1.3 First Order traversal1.3.1 Recursive Implementation
/***/publicvoid  preorderrecur (node node)    {if  Null) {        System.out.print (node.data//  root        //  left        //  right     }}
1.3.2 Non-recursive implementation

Implementation Method 1:

/*** Non-recursive first-order traversal*/ Public voidPreorder (node node) {Arraystack<Node> stack =NewArraystack<node> (n + 1);    Stack.push (node);  while(!Stack.isempty ()) {Node tmp=Stack.pop (); System.out.print (Tmp.data+ " ");//Root        if(Tmp.rchild! =NULL) {//if the right subtree of the root node is present, the right subtree is numbered into the stackStack.push (Tmp.rchild); }        if(Tmp.lchild! =NULL) {//if the left subtree of the root node is present, the left subtree is numbered into the stackStack.push (Tmp.lchild); }    }}

Implementation Method 2:

/*** Non-recursive first-order traversal*/ Public voidPreorderone (node node) {Arraystack<Node> stack =NewArraystack<node> (n + 1);  while(Node! =NULL|| !Stack.isempty ()) {         while(Node! =NULL){//put all the left-most into the stackSystem.out.print (Node.data + "");//RootStack.push (node); Node=Node.lchild; } Node tmp= Stack.pop ();//left subtree that pops up the last stacknode = Tmp.rchild;//See if it has a right child    }}
1.4 Middle Sequence traversal1.4.1 Recursive Implementation
/***/publicvoid  inorderrecur (node node)    {if  Null) {        //  left        //  root        //  Right     }}
1.4.2 Non-recursive implementation
/*** Non-recursive middle sequence traversal*/ Public voidinorder (node node) {Arraystack<Node> stack =NewArraystack<node> (n + 1);  while(Node! =NULL|| !Stack.isempty ()) {         while(Node! =NULL){//put all the left-most into the stackStack.push (node); Node=Node.lchild; } Node tmp= Stack.pop ();//left subtree that pops up the last stackSystem.out.print (Tmp.data + "");//go to the left subtree firstnode = Tmp.rchild;//See if it has a right child    }}
1.5 post-post traversal1.5.1 Recursive Implementation
/***/publicvoid  postorderrecur (node node)    {if  Null) {        //  left        //  right        //  root     }}
1.5.2 Non-recursive implementation
/*** Non-recursive post-traversal*/ Public voidPostorder (node node) {Arraystack<Node> stack =NewArraystack<node> (n + 1); Node Pre=NULL;//the node of the previous access     while(Node! =NULL|| !Stack.isempty ()) {         while(Node! =NULL){//put all the left-most into the stackStack.push (node); Node=Node.lchild; } Node tmp= Stack.peek ();//now to determine if there is a right child in the stack node, or whether the right child has visited//If the current node does not exist right child or right child has already visited, then access the current node        if(Tmp.rchild = =NULL|| Pre = =tmp.rchild) {Node n=Stack.pop (); System.out.print (N.data+ " ");//Access NodesPre =N; } Else{node= Tmp.rchild;//Otherwise access right child        }    }}
2 Testing
 Public Static voidMain (string[] args) {Linkbitree<Integer> Bitree =NewLinkbitree<integer>(); System.out.print ("First order Traversal (recursion):");    Bitree.preorderrecur (Bitree.getroot ()); System.out.print ("\ n sequence Traversal (recursive):");    Bitree.inorderrecur (Bitree.getroot ()); System.out.print ("\ nthe post-traversal (recursion):");    Bitree.postorderrecur (Bitree.getroot ()); System.out.print ("\ n Hierarchy Traversal:");    Bitree.levelorder (Bitree.getroot ()); System.out.print ("\ n Sequential traversal (non-recursive):");//Bitree.preorder (Bitree.getroot ());Bitree.preorderone (Bitree.getroot ()); System.out.print ("\ n sequence traversal (non-recursive):");    Bitree.inorder (Bitree.getroot ()); System.out.print ("\ nthe post-traversal (non-recursive):"); Bitree.postorder (Bitree.getroot ());}
2.1 Output Results

Binary tree chain storage and traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.