数据结构之二叉树篇卷一 -- 建立二叉树(With Java)

一、定义二叉树节点类

 1 package tree;
 2 
 3 public class Node<E> {
 4     public E data;
 5     public Node<E> lnode;
 6     public Node<E> rnode;
 7 
 8     public Node(){}
 9     public Node(E data) {
10         this.data = data;
11     }
12 }

  通过泛型(generics)定义了一个公有的节点类,包含一个数据域 data,以及两个引用域 lnode 和 rnode。构造函数提供有参和无参默认两种。当然,因为二叉树节点这个类的适用范围是在关于二叉树的操作中,所以更加完美的做法是将其作为私有内部类定义。

 

二、定义二叉树主类

 1 public class BiTree <E> {
 2     
 3     /** root node of the binary tree    */
 4     private Node<E> root;
 5     /** the gross of total leaves    */
 6     private int leaveGross;
 7     private int depth;
 8     private String name;
 9     
10     public BiTree(String name) {
11         this.name = name;
12         root = new Node<>();
13     }
14 
15     public Node<E> getRoot() { return root; }
16     
17     public int getLeaveGross() { return leaveGross; }
18 
19     public String getName() { return name; }
20 
21     public int getDepth() { return depth(root); }
22 
23     public int depth(Node<E> root){
24         if(root != null) {
25             return Math.max(depth(root.lnode), depth(root.rnode)) + 1;
26         } else
27             return 0;
28     }
29 }

  这里最主要的是根节点信息 root, 它是二叉树的构建、遍历、求深度、求叶子总数的根本。其他属性,可以有选择的定义。这里我递归写了一个求二叉树深度的方法。

 

 三、构造二叉树

  在主类<code>BiTree</code>中定义建立二叉树的方法 -- generate()。

 1     /**
 2      * Construct a Binary Tree with a given sequence of data as form of array.
 3      * The <code>data</code> should be given as a complete binary tree.
 4      * @param data
 5      * @author SheepCore@MarshallLee
 6      */
 7     public void generate(E[] data){
 8         if(data.length == 0)
 9             return;
10         int numData = data.length;
11         Node<E>[] nodes = new Node[numData];
12 
13         for (int i = 0; i < numData; i++) {
14             nodes[i] = new Node(data[i]);
15         }
16 
17         for (int i = 0; i < numData / 2; i++) {
18             nodes[i].lnode = nodes[2 * i + 1];
19             nodes[i].rnode = nodes[2 * i + 2] ;
20         }
21         this.root = nodes[0];
22         depth = getDepth();
23         leaveGross = numData;
24     }

 

posted @ 2019-09-24 19:13  SheepCore  阅读(312)  评论(0编辑  收藏  举报