在此示例中,我們將學(xué)習(xí)如何在Java中執(zhí)行順序樹(shù)遍歷。
class Node { int item; Node left, right; public Node(int key) { item = key; left = right = null; } } class Tree { //樹(shù)根 Node root; Tree() { root = null; } void inOrder(Node node) { if (node == null) return; //遍歷左子樹(shù) inOrder(node.left); //遍歷根節(jié)點(diǎn) System.out.print(node.item + "->"); //遍歷右子樹(shù) inOrder(node.right); } public static void main(String[] args) { //創(chuàng)建一個(gè)Tree對(duì)象 Tree tree = new Tree(); //創(chuàng)建樹(shù)的節(jié)點(diǎn) tree.root = new Node(1); tree.root.left = new Node(12); tree.root.right = new Node(9); //創(chuàng)建左子節(jié)點(diǎn)的子節(jié)點(diǎn) tree.root.left.left = new Node(5); tree.root.left.right = new Node(6); System.out.println("按順序遍歷"); tree.inOrder(tree.root); } }
輸出結(jié)果
按順序遍歷 5->12->6->1->9->
在上面的示例中,我們已經(jīng)用Java實(shí)現(xiàn)了樹(shù)數(shù)據(jù)結(jié)構(gòu)。在這里,我們正在執(zhí)行樹(shù)的有序遍歷。