⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tree.java

📁 用java实现二叉树的建立
💻 JAVA
字号:
class Tree
{
 private Node root; 

 public Node find(int key) // 寻找给定的根结点
 { 
  Node current = root; 
  while(current.iData != key) 
  {
   if(key < current.iData) 
    current = current.leftChild;//赋给左儿子
   else
    current = current.rightChild; // 赋给右儿子
   if(current == null) 
    return null; 
  } 
  return current; 
 }

 public void insert(int id)//创建新结点
 {
  Node newNode = new Node(); 
  newNode.iData = id; 
    if(root==null) 
   root = newNode;
  else 
  {
   Node current = root; 
   Node parent;
   while(true) 
   {
    parent = current;
    if(id < current.iData) 
    {
     current = current.leftChild;
     if(current == null) 
     { 
      parent.leftChild = newNode;
      return;
     }
    } 
    else 
    {
     current = current.rightChild;
     if(current == null) 
     { 
      parent.rightChild = newNode;
      return;
     }
    } 
   } 
  } 
 } 
 
 public void printTree(){
  System.out.print("前序遍历:");
  preOrder(root);
  System.out.println();
  System.out.print("中序遍历:");
  inOrder(root);
  System.out.println();
  System.out.print("后序遍历:");
  postOrder(root);
  System.out.println();
 }
  

 private void preOrder(Node localRoot)
 {
  if(localRoot !=null)
  {
   localRoot.displayNode();
   preOrder(localRoot.leftChild);
   preOrder(localRoot.rightChild);
  }
 }

 private void inOrder(Node localRoot)
 {
  if(localRoot != null)
  {
   inOrder(localRoot.leftChild);
   localRoot.displayNode();
   inOrder(localRoot.rightChild);
  }
 }

 private void postOrder(Node localRoot)
 {
  if(localRoot !=null)
  {
   postOrder(localRoot.leftChild);
   postOrder(localRoot.rightChild);
   localRoot.displayNode();
  }
 }
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -