將乙個陣列變成二叉樹

2021-07-28 08:33:08 字數 1136 閱讀 8437

二叉樹是每個節點最多有兩個子樹的樹結構。通常子樹被稱作 「左子樹」 和 「右子樹」。

比如陣列:

int array =

變為二叉樹為:

分析:1、首先要定義每乙個結點,每乙個結點包括自身值,左結點和右結點,實現get、set方法。

public class node

public node(int data, node left, node right)

public int getdata()

public void setdata(int data)

public node getleft()

public void setleft(node left)

public node getright()

public void setright(node right)

}2、建立二叉樹

public class demo2

// 構建二叉樹

if (list.size() > 0)

if (list.get(2 * i + 2) != null)

}// 判斷

最後乙個根結點

:因為最後乙個根結點可能沒有右結點,所以單獨拿出來處理

int lastindex = array.length / 2 - 1;

// 左結點

list.get(lastindex).left = list.get(lastindex * 2 + 1);

// 右結點,如果陣列的長度為奇數才有右結點

if (array.length % 2 == 1)

}}// 遍歷,先序遍歷

public static void print(node node)

}   public static void main(string args) ;

demo2 demo = new demo2();

demo.createtree(array);

print(list.get(0));

}}結果為:

1 2 4 8 9 5 3 6 7 

30 將乙個陣列 二叉樹 , 調整成乙個大頂堆

功能 完成 將 以 i 對應的非葉子結點的樹調整成大頂堆 舉例 int arr i 1 adjustheap 得到 如果我們再次呼叫 adjustheap 傳入的是 i 0 得到 param arr 待調整的陣列 param i 表示非葉子結點在陣列中索引 param lenght 表示對多少個元素...

二叉樹 判斷乙個樹是否是平衡二叉樹

題目 給定乙個二叉樹,判斷其是否是平衡二叉樹。方法一 bool isbalancedtree treenode root bool ltree isbalancedtree root left bool rtree isbalancedtree root right if ltree rtree r...

二叉樹 二叉樹的下乙個結點

題目描述 給定一棵二叉樹和乙個結點,要求找到中序遍歷此樹時該結點的下乙個結點。分析 中序遍歷一棵二叉樹時,要根據乙個結點有無右子樹而分開討論。若當前結點有右子樹,則它的下乙個結點就是其右子樹的最左葉子結點 若當前結點沒有右子樹,那麼又分兩種情況 若當前結點是其父節點的左孩子結點,那麼其下乙個結點就是...