將一個數組變成二叉樹
二叉樹是每個節點最多有兩個子樹的樹結構。通常子樹被稱作 “左子樹” 和 “右子樹”。
比如陣列:
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}
變為二叉樹為:
分析:
1、首先要定義每一個結點,每一個結點包括自身值,左結點和右結點,實現get、set方法。
public class Node {
public int data; //自己本身值
public Node left; //左結點
public Node right; //右結點
public Node() {
}
public Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
2、建立二叉樹
public class Demo2 {
public static List<Node> list = new ArrayList<Node>(); //用一個集合來存放每一個Node
public void createTree(int[] array) {
for (int i = 0; i < array.length; i++) {
Node node = new Node(array[i], null, null); //建立結點,每一個結點的左結點和右結點為null
list.add(node); // list中存著每一個結點
}
// 構建二叉樹
if (list.size() > 0) {
for (int i = 0; i < array.length / 2 - 1; i++) { // i表示的是根節點的索引,從0開始
if (list.get(2 * i + 1) != null) {
// 左結點
list.get(i).left = list.get(2 * i + 1);
}
if (list.get(2 * i + 2) != null) {
// 右結點
list.get(i).right = list.get(2 * i + 2);
}
}
// 判斷最後一個根結點:因為最後一個根結點可能沒有右結點,所以單獨拿出來處理
int lastIndex = array.length / 2 - 1;
// 左結點
list.get(lastIndex).left = list.get(lastIndex * 2 + 1);
// 右結點,如果陣列的長度為奇數才有右結點
if (array.length % 2 == 1) {
list.get(lastIndex).right = list.get(lastIndex * 2 + 2);
}
}
}
// 遍歷,先序遍歷
public static void print(Node node) {
if (node != null) {
System.out.print(node.data + " ");
print(node.left);
print(node.right);
}
}
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Demo2 demo = new Demo2();
demo.createTree(array);
print(list.get(0));
}
}
結果為:
1 2 4 8 9 5 3 6 7