二叉樹 儲存 遍歷

2021-10-14 21:43:52 字數 1907 閱讀 9284

樹的每個節點最多有兩個孩子節點

乙個節點編號i,它的雙親i/2,左孩子2i,右孩子2i+1

先序遍歷:根左右

中序遍歷:左根右

後續遍歷:左右根

//二叉樹節點是個靜態類

private static class treenode

//構建二叉樹

//傳入乙個集合序列,linkedlist適合插入資料,頻繁刪除資料,每次存入資料後都要刪除存入的資料

public static treenode creatbinarytree(linkedlistinputlist)

int data=inputlist.removefirst();//移除第乙個元素,並拿到他

if(data!=null)//有資料 }

//先序遍歷

public void preorder(treenode node)

system.out.println(node.data);//輸出資料,遍歷根

preorder(node.leftchild);//遍歷左孩子

preorder(node.rightchild);//遍歷右孩子

} //注意:data不用再判斷,因為空也可以輸出,前面構造二叉樹時,data=null時,也存入了

//中序遍歷

public void inorder(treenode node)

inorder(node.leftchild);//遍歷左孩子

system.out.println(node.data);//輸出資料,遍歷根

inorder(node.rightchild);//遍歷右孩子

} //後序遍歷

public void postorder(treenode node)

postorder(node.leftchild);//遍歷左孩子

postorder(node.rightchild);//遍歷右孩子

system.out.println(node.data);//輸出資料,遍歷根

} //主函式

public static void main(string args)

) );

treenode treenode =creatbinarytree(inputlist);

system.out.println(先序遍歷);

preorder(inputlist);

system.out.println(中序遍歷);

inorder(inputlist);

system.out.println(後序遍歷);

postorder(inputlist);

}要點

定義:三成員

建立:傳集合、兩判斷   

判斷一:集合為null,返回null.      

判斷二:元素為null,返回node

遍歷:判節點

節點為null,結束乙個節點遍歷

child  孩子

preorder 先序遍歷

inorder 中序遍歷

postorder 後序遍歷

createbinarytree 構建二叉樹

二叉樹的遍歷 二叉樹遍歷與儲存

在資料結構中,二叉樹是非常重要的結構。例如 資料庫中經常用到b 樹結構。那麼資料庫是如何去單個查詢或者範圍查詢?首先得理解二叉樹的幾種遍歷順序 先序 中序 後序 層次遍歷。先序 根節點 左子樹 右子樹 中序 左子樹 根節點 右子樹 後序 左子樹 右子樹 根節點 按層級 class node if c...

二叉樹儲存及遍歷

二叉樹儲存及遍歷 1 樹的儲存 注意 樹的深度是從根節點開始 其深度為1 自頂向下逐層累加的,而高度是從葉節點開始 其高度為1 自底向上逐層累加的。雖然樹的深度和高度一樣,但是具體到樹的某個節點,其深度和高度是不一樣的。我的理解是 非根非葉結點的深度是從根節點數到它的,高度是從葉節點數到它的。二叉樹...

二叉樹陣列儲存 前序遍歷 列印二叉樹

include stdafx.h include define size 20 求深度 完全二叉樹的最大節點數量s 2 n 1,n 樹的高度 對於乙個陣列結構的tree,要先求tree的深度n,求最大指數2 n 1 size 2 n size 1 所以 n log2 size 1 n向上取整 int...