zoukankan      html  css  js  c++  java
  • 数据结构与算法-第12章二叉树和其他树-001遍历

    以下例子的树是存在数组中

    1.中序遍历

     1 package chapter12Tree;
     2 
     3 public class ArrayBinaryTreeWithInorder
     4 {
     5    // data members
     6    static Object [] a;   // array that contains the tree
     7    static int last;      // position of last element in array a
     8 
     9    /** visit method that prints the element in a[i] */ 
    10    public static void visit(int i)
    11       {System.out.print(a[i] + " ");}
    12 
    13 
    14    /** inorder traversal */
    15    public static void inOrder(Object [] theArray, int theLast)
    16    {
    17       // set static data members
    18       a = theArray;
    19       last = theLast;
    20 
    21       // start the recursive traversal method at the root
    22       theInOrder(1);
    23    }
    24 
    25    /** actual method to do the inorder traversal */
    26    static void theInOrder(int i)
    27    {// traverse subtree rooted at a[i]
    28       if (i <= last && a[i] != null)
    29       {// root exists
    30          theInOrder(2 * i);         // do left subtree
    31          visit(i);                  // visit tree root
    32          theInOrder(2 * i + 1);     // do right subtree
    33       }
    34    }
    35    
    36    public static void main(String[] args) {
    37        Object [] a = {0,1,2,3,4,5}; //第一个位置没用
    38        inOrder(a, a.length-1); //输出4 2 5 1 3 
    39    }
    40 }

    2.平层遍历

     1 package chapter12Tree;
     2 
     3 //Since the elements are stored in the array by levels, 
     4 //a level order traversal may be done by examining the array 
     5 //from left to right. The code is given below. 
     6 public class ArrayBinaryTreeWithLevelOrder
     7 {
     8    static Object [] a;   // array that contains the tree
     9 
    10    /** visit method that prints the element in a[i] */ 
    11    public static void visit(int i)
    12       {System.out.print(a[i] + " ");}
    13 
    14    /** level order traversal */
    15    public static void levelOrder(Object [] theArray, int last)
    16    {
    17       a = theArray;
    18       for (int i = 1; i <= last; i++)
    19          if (a[i] != null)
    20             visit(i);  
    21    }
    22    
    23    public static void main(String[] args) {
    24        Object [] a = {0,1,2,3,4,5}; //第一个位置没用
    25        levelOrder(a, a.length-1); //输出1 2 3 4 5  
    26    }
    27 }
  • 相关阅读:
    tyvj 1031 热浪 最短路
    【bzoj2005】 [Noi2010]能量采集 数学结论(gcd)
    hdu 1394 Minimum Inversion Number 逆序数/树状数组
    HDU 1698 just a hook 线段树,区间定值,求和
    ZeptoLab Code Rush 2015 C. Om Nom and Candies 暴力
    ZeptoLab Code Rush 2015 B. Om Nom and Dark Park DFS
    ZeptoLab Code Rush 2015 A. King of Thieves 暴力
    hdoj 5199 Gunner map
    hdoj 5198 Strange Class 水题
    vijos 1659 河蟹王国 线段树区间加、区间查询最大值
  • 原文地址:https://www.cnblogs.com/shamgod/p/5295525.html
Copyright © 2011-2022 走看看