Do a breadth first traversal of a tree

来源:互联网 发布:域名备案到期 编辑:程序博客网 时间:2024/06/03 14:23

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

class BinaryTree {

 static class Node {
  char data;
  Node left = null;
  Node right = null;
  int i;
 }

 public static char[] dataArray = new char[] { 'a', 'b', 'c', 'd', 'e', 'f',
   'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' };

 public static Node creatRoot(Node node) {
  if (node.i < dataArray.length) {
   if (node.data == '-')
    node = null;
   if (node != null)
    node.data = dataArray[node.i];
   node.left = creatLeft(node);
   node.right = creatRight(node);

  }
  return node;
 }

 public static Node creatLeft(Node node) {
  if (node != null) {
   node.left = new Node();
   node.left.i = 2 * node.i + 1;
   creatRoot(node.left);
  }
  return node.left;

 }

 public static Node creatRight(Node node) {
  if (node != null) {
   node.right = new Node();
   node.right.i = 2 * node.i + 2;
   creatRoot(node.right);
  }
  return node.right;
 }

 public static void preOrder(Node node) {
  if (node != null) {
   System.out.print(node.data + " ");
   preOrder(node.left);
   preOrder(node.right);
  }
 }

 public static void inOrder(Node node) {
  if (node != null) {
   inOrder(node.left);
   System.out.print(node.data + " ");
   inOrder(node.right);
  }
 }

 public static void postOrder(Node node) {

  if (node != null) {
   postOrder(node.left);
   postOrder(node.right);
   System.out.print(node.data + " ");

  }
 }

 public static void breadthFirstTraversal(Node node) {
  Node p=node;
  Queue<Node> queue = new LinkedList<Node>();
  queue.add(node);
  while (!queue.isEmpty()) {
   p = queue.poll();
   System.out.print(p.data + " ");
   if (p.left != null) {
    queue.add(p.left);}
   if (p.right != null) {  //不能是else if
    queue.add(p.right);
   }
   
  }
 }

 public static void main(String args[]) {
  Node node = new Node();

  node = creatRoot(node);

  preOrder(node);
  System.out.println();
  inOrder(node);
  System.out.println();
  postOrder(node);
  System.out.println();
  System.out.print(depth(node) - 1);
  System.out.println();
  breadthFirstTraversal(node);
 }

 public static int depth(Node node) {
  int lDepth, rDepth;
  if (node == null) {
   return 0;
  }
  lDepth = depth(node.left);
  rDepth = depth(node.right);
  return (lDepth > rDepth ? lDepth : rDepth) + 1;
 }

}

原创粉丝点击