コード例 #1
0
 static BinaryTreeNode buildBinaryTree(char[] preOrder, char[] inOrder, int start, int end) {
   if (start > end) return null;
   BinaryTreeNode rootNode = new BinaryTreeNode();
   rootNode.setData(preOrder[preIndex]);
   preIndex++;
   // System.out.println(rootNode.getData());
   if (start == end) return rootNode;
   int dataIndex = search(inOrder, start, end, rootNode.getData());
   if (dataIndex == -1) return null;
   // System.out.println("Left Bounds: "+start+" "+(dataIndex-1));
   rootNode.setLeft(buildBinaryTree(preOrder, inOrder, start, dataIndex - 1));
   // System.out.println("Right Bounds: "+(dataIndex+1)+" "+end);
   rootNode.setRight(buildBinaryTree(preOrder, inOrder, dataIndex + 1, end));
   return rootNode;
 }
コード例 #2
0
  public static void levelTravesal(BinaryTreeNode node) {
    Queue queue = new LinkedList();

    if (node == null) return;
    queue.offer(node);
    queue.offer(null);
    int level = 0;
    while (!queue.isEmpty()) {
      BinaryTreeNode temp = (BinaryTreeNode) queue.poll();

      if (temp == null) {
        System.out.println("Level: " + level);
        if (!queue.isEmpty()) queue.offer(null);
        level++;
      } else {

        System.out.println(temp.data);

        if (temp.getLeft() != null) queue.offer(temp.getLeft());

        if (temp.getRight() != null) queue.offer(temp.getRight());
      }
    }
  }