现在的位置: 首页 > 综合 > 正文

二叉树的java构建和三种遍历方式

2018年01月29日 ⁄ 综合 ⁄ 共 1829字 ⁄ 字号 评论关闭

 

二.代码,两个class

Java代码  收藏代码
  1. public class Node {  
  2.     /** 名称 */  
  3.     private String name;  
  4.   
  5.     /** 左节点 */  
  6.     private Node left;  
  7.   
  8.     /** 右节点 */  
  9.     private Node right;  
  10.    
  11. //get.set略  
  12.     public Node(String n, Node l, Node r) {  
  13.         name = n;  
  14.         left = l;  
  15.         right = r;  
  16.     }  
  17. }  

 

Java代码  收藏代码
  1. public class Admin {  
  2.     public static void main(String[] args) {  
  3.         test();  
  4.     }  
  5.   
  6.     private static void test() {  
  7.         // 先序  
  8.         xian(init());  
  9.         System.out.println();  
  10.         // 中序  
  11.         zhong(init());  
  12.         System.out.println();  
  13.         // 后序  
  14.         hou(init());  
  15.     }  
  16.   
  17.     /** 初始化 */  
  18.     private static Node init() {  
  19.         Node nodeG = new Node("G"nullnull);  
  20.         Node nodeF = new Node("F"nullnull);  
  21.         Node nodeE = new Node("E"nullnull);  
  22.         Node nodeD = new Node("D"null, nodeG);  
  23.         Node nodeC = new Node("C", nodeF, null);  
  24.         Node nodeB = new Node("B", nodeD, nodeE);  
  25.         Node nodeA = new Node("A", nodeB, nodeC);  
  26.         return nodeA;  
  27.     }  
  28.   
  29.     private static void print(Node node) {  
  30.         System.out.print(node.getName() + "==>");  
  31.     }  
  32.   
  33.     /** 先序 中->左->右 */  
  34.     public static void xian(Node node) {  
  35.         if (node != null) {  
  36.             print(node);  
  37.             xian(node.getLeft());  
  38.             xian(node.getRight());  
  39.         }  
  40.     }  
  41.   
  42.     /** 中序 左->中->右 */  
  43.     public static void zhong(Node node) {  
  44.         if (node != null) {  
  45.             zhong(node.getLeft());  
  46.             print(node);  
  47.             zhong(node.getRight());  
  48.         }  
  49.     }  
  50.   
  51.     /** 后序 左->右->中 */  
  52.     public static void hou(Node node) {  
  53.         if (node != null) {  
  54.             hou(node.getLeft());  
  55.             hou(node.getRight());  
  56.             print(node);  
  57.         }  
  58.     }  

转载地址:http://xiaojianhx.iteye.com/blog/491481

抱歉!评论已关闭.