Java implementation of two tree-related code-----data structure

Source: Internet
Author: User

Interface

/*1. Development time: 2014-11-5 *2. Developer: Zhaoyuan  *3. Maintainer: 赵远  *3. Program Description: Tree interface  *4. NOTE: no  * **/package Tree;import Tree.node;public  interface treenode {// class node {}; // 1.  finding the number of nodes in a binary tree  int  Getnodenum (node root); // 2.  to find the depth of the binary tree  int getdepth (node root); //  3.  Pre-sequence traversal, middle sequence traversal, post-order traversal  void preordertraverse (node root);  void inordertraverse (node  root);  void postordertraverse (node root);  // 4. Layered traversal of the binary tree (from top to bottom, from left to right)  void  leveltraverse (Node root);// 5.  The two-fork lookup tree into an ordered doubly linked list// 6.  the number of nodes in the K-tier of the binary tree// 7.   Finding the number of leaf nodes in a binary tree// 8.  determine if two binary trees are structurally identical// 9.  determine if the binary tree is a balanced binary tree// 10.  to find the image of the binary tree//  11.  the lowest common ancestor node of two nodes in a binary tree// 12.  the maximum distance of the nodes in the binary tree// 13.  the binary tree// 14 is reconstructed by the sequence traversal sequence and the middle sequence traversal sequences. Determine if the binary tree is not a complete binary tree} 

Node

Package tree;//* node class. public class Node {public Object data;//value stored by the node. public node leftchild; A reference to the left Dial hand node. public node Rightchild; A reference to the right child node.  Public node (Object value) {this.data = value;  Leftchild = null; Rightchild = null; }}

Specific implementation

/*1. Development time: 2014-11-13 *2. Developer: Zhaoyuan  *3. Maintainer: Zhaoyuan  *3. Program Description: Two the method of the tree is  *4. Precautions: No  * **/ Package tree;import tree.node;import tree.arrayqueue;public class binarytreenode  implements TreeNode { private node root; //  root node  binarytreenode ()  {  root = null; } // 1.  finding the number of nodes in a binary tree  //  recursive solution:  //   (1) If the binary tree is empty, the number of nodes is 0 //  (2) If the binary tree is not empty, the number of binary tree nodes  =  the number of left dial hand tree nodes  +  the number of right subtree nodes  + 1  public int getnodenum (Node root)  {  if  (root == null)     Recursive export    return 0;  return getnodenum (root.rightchild)  +  Getnodenum (Root.leftchild)  + 1; }; // 2.  finding the depth  //  recursive solution of binary tree:  //   (1) If the binary tree is empty, the depth of the binary tree is 0 //  (2) If the binary tree is not empty, the depth of the binary tree is  = max (the left subtree depth,  the right sub-tree depth)  + 1  public int getdeptH (node root)  {  if  (root == null)  //  recursive exit    return  0;  int depthleft = getdepth (root.leftchild);   int depthright  = getdepth (root.rightchild);   return depthleft > depthright ?   (depthleft + 1)  :  (depthright + 1); }; // 3.  pre-sequence traversal, middle sequence traversal , post-order traversal  //  pre-sequence traversal recursive solution: //  (1) If the binary tree is empty, the empty Operation  //  (2) If the binary tree is not empty, accesses the root node, the pre-sequence traverses the left subtree, and the pre-sequence traverses the right subtree  / / private void visit (node root) {function Independent  // if  (root == null)  //  return ; // system.out.print ("...");  // visit (Root.leftchild); //  Pre-sequence traversal left subtree  // visit (root.rightchild); //  pre-sequence traversal right sub-tree  // }; public void  Preordertraverse (Node root)  {  if  (root == null)    return;   system.ouT.print (root.data +  " ");   preordertraverse (Root.leftchild);   Preordertraverse (Root.rightchild);   // visit (root);  function independent  }; //  sequential traversal recursive solution  //  (1) If the binary tree is empty, empty operation.  //  (2) If the binary tree is not empty, the middle sequence traverses the left subtree, accesses the root node, and the middle sequence traverses the right subtree  public void inordertraverse (node root)  {  if  (root == null)    return;  inordertraverse ( Root.leftchild)   system.out.print (root.data +  " ");   inordertraverse ( Root.rightchild);  // }; //  post-order traversal recursive solution  //  (1) If the binary tree is empty, empty operation  //  (2) If the binary tree is not empty, the post-order traversal of the left subtree, the subsequent traversal of the right subtree, access to the root node  public void postordertraverse (node root)  {   postordertraverse (Root.leftchild);   postordertraverse (Root.rightchild);   System.out.print (root.data +  " ");  }; // 4. Layered traversal of a binary tree (from top to bottom, from left to right)  //  The queue is initialized, and the root node is pressed into the queue.  //  when the queue is not empty,Do the following: Popup a node, access, if the left child node or right sub-section  //  point is not empty, press it into the queue.  public void leveltraverse (node root)  {  arrayqueue q = new  arrayqueue ();  if  (root == null)    return;  q.enqueue ( Root);  while  (!q.isempty ())  {   root.data = q.getfront ();    q.dequeue ();    system.out.print (root.data +  " "); //  access node    if  (root.leftchild != null)     q.enqueue (root.leftchild);    if  (root.rightchild != null)     q.enqueue (root.rightchild ;  }  return; }// 5.  the number of nodes in the K-layer of the binary tree//  recursive solution://  (1) If the binary tree is empty or k< 1 returns 0//  (2) If the binary tree is not empty and k==1, returns 1//  (3) If the binary tree is not empty and k>1, the number of nodes that return record k-1 layer and the number of nodes in the right subtree k-1 layer  int  Getnodenumkthlevel (node root, int k)    { &nbsP;     if (root == null | | &NBSP;K&NBSP;&LT;&NBSP;1)            return 0;        if (k == 1)             return 1;       int numLeft =  Getnodenumkthlevel (root.leftchild, k-1); //  record k-1 layer node number         int numright = getnodenumkthlevel (Root.rightchild, k-1) The number of nodes in the k-1 layer of the; //  right subtree        return  (numleft + numright);   }   // 6.  finding the number of leaf nodes in binary tree//  recursive solution://  (1) If the binary tree is empty, return 0//  (2) If the binary tree is not empty and the left and right subtrees are empty, return 1//  (3) If the binary tree is not empty, and the left and right subtrees are not empty at the same time, return the number of leaves in the subtree plus the number of leaf nodes in the subtree  int getleafnodenum (node root)     {       if (root == null)            return 0;        if (root.leftchild == null && root.rightchild == null)             return 1;        int numleft = getleafnodenum (Root.leftchild) The number of nodes in the; //  left dial hand tree         int numright = getleafnodenum (Root.leftchild) The number of nodes in the middle of the right sub-tree of; //         return  (numleft + numright);   }    // 7.  determine if two binary trees are structurally identical//  does not consider data content. The same structure means that the corresponding Zuozi and corresponding right sub-tree are all structurally identical.   Recursive solution://  (1) If two binary trees are empty, return True//  (2) If two binary trees are empty, the other is not empty, and the other tree is not NULL, return False//  (3) If two binary trees are not empty, If the corresponding Saozi right subtree is isomorphic back to true, the other returns False  boolean structurecmp (Node root1, node root2)     {       if (root1 == null && root2 == null)  //  all empty, return to True             return true;       else if ( root1 == null | |  root2 == null)  //  has one empty, one not empty, returns false             return false;       boolean resultleft = &NBSP;STRUCTURECMP (root1.leftchild,root2.leftchild); //  compare left dial hand tree        &NBSP;&NBSP;BOOLEAN&NBSP;RESULTRIGHT&NBSP;=&NBSP;STRUCTURECMP (root1.rightchild, root2.rightchild);  / /  relative to right subtree        return  (resultleft &&  Resultright);   }   // 8.  Determine if the binary tree is not a balanced binary tree//  recursive solution://  (1) If the binary tree is empty , Return True//  (2) If the binary tree is not empty, if the Saozi right subtree is the AVL tree and the Saozi right subtree height difference is not greater than 1, returns True, the other returns False  boolean isavl (NODE&NBSP;ROOT,&NBSp;int  height)    {       if (root ==  NULL)  //  empty tree, return True        {            height = 0;            return true;       }        int heightleft = 0;       boolean resultleft =  isavl (root.leftchild, heightleft);        int heightright &NBSP;=&NBSP;0;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BOOLEAN&NBSP;RESULTRIGHT&NBSP;=&NBSP;ISAVL ( Root.rightchild, heightright);        if (resultLeft &&  resultright && abs (heightleft - heightright)  <= 1)  //   Saozi Right subtree are AVL, and the height difference is not greater than 1, return true        {           height =  max (heightleft, heightright)  + 1;            return true;       }        else       {            height = max (heightleft, heightright)  + 1;            return false;       }    } private int max (int heightleft, int heightright)  {   Return heightleft>heightright?heightleft:heightright; } private int abs (int i )  {  if (i>0)  return i;  else return -i; }    //9. Recursive method Insert Node   p Ublic node insert (node root, object x)  {     node  p = null ;     p.data=x;      P.leftchild=null;     p.rightchild=null;     if (root ==  null) {         root = p;          }                 else if (root.leftchild== null) {      root.leftchild  = insert (root.leftchild,x);         }      else if (root.rightchild== null) {          root.rightchild= insert (root.rightchild,x);          }      return root; }} 

referencing a queue

package tree;/** * *  @author   Classes  */public class ArrayQueue  implements queue {    private object[] data;     Private int front;    private int rear;    public  arrayqueue (int capacity)  {        this.data =  new Object[capacity];        this.front =  This.rear = 0;    }    public arrayqueue ()  {         this (1024x768);     }    public  void clear ()  {        this.front = this.rear  = 0;    }    public boolean isempty ()  {         return this.front == this.rear;    }     Public object getfront ()  {        if  (IsEmpty ())  {            throw new  Unsupportedoperationexception ("Queue is empty");        }         return data[front];    }    public  void enqueue (Object o)  {        if  (Isfull () )  {            throw new  Unsupportedoperationexception ("queue is full");        }         this.data[rear++] = o;         rear %= data.length;    }     public object dequeue ()  {         throw new unsupportedoperationexception ("Not supported yet.");  //To change body of generated methods, choose Tools |  Templates.    }    private boolean isfull ()  {         return  ((rear + 1)  % data.length)  ==  front;    }}

Java implementation of two tree-related code-----data structure

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.