Java完全二叉树的创建与四种遍历方法分析

  

本文实例讲述了Java完全二叉树的创建与四种遍历方法。分享给大家供大家参考,具体如下:

  

有如下的一颗完全二叉树:

  

癑ava完全二叉树的创建与四种遍历方法分析"

  

先序遍历结果应该为:1,2,4,5,3,6,7
  中序遍历结果应该为:4,2,5,1,6,3,7
  后序遍历结果应该为:4,5,2,6,7,3,1
  层序遍历结果应该为:1,2,3,4,5,6,7

  

二叉树的先序遍历,中序遍历,后序遍历其实都是一样的,都是执行递归操作。

  

我这记录一下层次遍历吧:层次遍历需要用到队列,先入队在出队,每次出队的元素检查是其是否有左右孩子,有则将其加入队列,由于利用队列的先进先出原理,进行层次遍历。

  

下面记录下完整代码(java实现),包括几种遍历方法:

        进口java.util.ArrayDeque;   进口java.util.ArrayList;   进口并不知道;   进口java.util.Queue;/* *   *定义二叉树节点元素   * @author泡沫   *   */{类节点   公共节点leftchild;   公共节点rightchild;   公共int数据;   公共节点(int数据){   这一点。数据=https://www.yisu.com/zixun/data;   }   }   公开课TestBinTree {/* *   数*将一个进行组构建成一个完全二叉树   * @param arr需要构建的数组   * @return二叉树的根节点   */公共节点initBinTree (int [] arr) {   如果(加勒比海盗。长度==1){   返回新节点(arr [0]);   }   <节点列表>节点列表=new ArrayList <> ();   for (int i=0;我 nodeQueue) {   nodeQueue.add(根);   节点temp=零;   在((temp=nodeQueue.poll ()) !=null) {   System.out.print (temp。数据+ " ");   如果(temp.leftchild !=null) {   nodeQueue.add (temp.leftchild);   }   如果(temp.rightchild !=null) {   nodeQueue.add (temp.rightchild);   }   }   }/* *   *先序遍历   * @param根二叉树根节点   */公共空间preTrival(根节点){   如果(root==null) {   返回;   }   System.out.print(根。数据+ " ");   preTrival (root.leftchild);   preTrival (root.rightchild);   }/* *   *中序遍历   * @param根二叉树根节点   */公共空间midTrival(根节点){   如果(root==null) {   返回;   }   midTrival (root.leftchild);   System.out.print(根。数据+ " ");   midTrival (root.rightchild);   }/* *   *后序遍历   * @param根二叉树根节点   */公共空间afterTrival(根节点){   如果(root==null) {   返回;   }   afterTrival (root.leftchild);   afterTrival (root.rightchild);   System.out.print(根。数据+ " ");   }   公共静态void main (String [] args) {   TestBinTree btree=new TestBinTree ();   arr int []=new int [] {1, 2, 3, 4, 5, 6, 7};   根节点=btree.initBinTree (arr);   Queue,nodeQueue=new ArrayDeque<的在();   System.out.println(“测试结果:”);   System.out.println(“层序遍历:”);   来。trivalBinTree(根,nodeQueue);   System.out.println (“\ n先序遍历:”);   btree.preTrival(根);   System.out.println (“\ n中序遍历:”);   btree.midTrival(根);   System.out.println (“\ n后序遍历:”);   btree.afterTrival(根);   }   }      之前      

运行结果:

  

癑ava完全二叉树的创建与四种遍历方法分析"

  

  

满二叉树是指这样的一种二叉树:除最后一层外,每一层上的所有结点都有两个子结点。在满二叉树中,每一层上的结点数都达到最大值,即在满二叉树的第k层上有2 k - 1个结点,且深度为m的满二叉树有2 m - 1个结点。

  

完全二叉树是指这样的二叉树:除最后一层外,每一层上的结点数均达到最大值;在最后一层上只缺少右边的若干结点。

Java完全二叉树的创建与四种遍历方法分析