ningxiaofeng 发表于 2013-2-3 11:15:40

转帖 JAVA 二叉树 实现

原帖地址:http://topic.csdn.net/u/20090218/17/6f07b6db-5019-4102-bc72-cc4db3eae890.html
1)要求   <!-- google_ad_section_start -->用java写二叉树算法,实现添加数据形成二叉树功能,并以先序的方式打印出来:
定义Node
public class Node {
 public int key;
 
 Node right;
 
 Node left;
 public Node(int key) {
  this.key = key;
 }
 public String toString() {
  return "my key is " + key;
 }
}
定义二叉树
public class Tree {
 public Node root;
 public Node findNode(Node node) {
  Node current = root;
  while (current.key != node.key) {
   if (current.key > node.key) {
    current = current.left;
   } else {
    current = current.right;
   }
   if (current == null) {
    return null;
   }
  }
  return current;
 }
 public void insertNode(Node node) {
  if (root == null) {
   root = node;
  } else {
   Node current = root;
   Node parent;
   while (true) {
    parent = current;
    if (current.key > node.key) {
     current = current.left;
     if (current == null) {
      parent.left = node;
      return;
     }
    } else {
     current = current.right;
     if (current == null) {
      parent.right = node;
      return;
     }
    }
   }
  }
 }
 public void inOrder(Node current) {
  if (current != null) {
   inOrder(current.left);
   System.out.println(current);
   inOrder(current.right);
  }
 }
}
页: [1]
查看完整版本: 转帖 JAVA 二叉树 实现