`
ningxiaofeng
  • 浏览: 6429 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

转帖 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);
  }
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics