Chương trình Java để thực hiện duyệt cây inorder

Trong ví dụ này, chúng ta sẽ học cách thực hiện duyệt cây inorder trong Java.

Để hiểu ví dụ này, bạn nên có kiến ​​thức về các chủ đề lập trình Java sau:

  • Lớp và đối tượng Java
  • Phương thức Java

Ví dụ: Chương trình Java để thực hiện duyệt cây inorder

 class Node ( int item; Node left, right; public Node(int key) ( item = key; left = right = null; ) ) class Tree ( // root of Tree Node root; Tree() ( root = null; ) void inOrder(Node node) ( if (node == null) return; // traverse the left child inOrder(node.left); // traverse the root node System.out.print(node.item + "->"); // traverse the right child inOrder(node.right); ) public static void main(String() args) ( // create an object of Tree Tree tree = new Tree(); // create nodes of tree tree.root = new Node(1); tree.root.left = new Node(12); tree.root.right = new Node(9); // create child nodes of left child tree.root.left.left = new Node(5); tree.root.left.right = new Node(6); System.out.println("In Order traversal"); tree.inOrder(tree.root); ) )
Inorder Tree Traversal

Đầu ra

 Theo thứ tự truyền 5-> 12-> 6-> 1-> 9->

Trong ví dụ trên, chúng ta đã triển khai cấu trúc dữ liệu cây trong Java. Ở đây, chúng tôi đang thực hiện việc đi ngang qua cây nhỏ hơn.

Đề xuất đọc :

  • Cấu trúc dữ liệu cây nhị phân
  • Traversal cây
  • Triển khai cây nhị phân trong Java

thú vị bài viết...