执行中序树遍历的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例:执行中序树遍历的 Java 程序

public class Node {
  int item;
  Node left, right;

  public Node(int key) {
  item = key;
  left = right = null;
  }
}

public 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);
  }
}

输出

In Order traversal
5->12->6->1->9->

在上面的例子中,我们已经用 Java 实现了树数据结构。在这里,我们正在执行树的中序遍历。

推荐阅读