`

二叉树

阅读更多
二叉树

无序数组: 查找删除慢,大小固定
有序数组:插入慢 删除幔
链表:查找慢,插入和删除慢

树的相关概念:
树: 由边连接着节点而构成

根: 树顶端的节点称为根,一棵树只有一个根
父节点:每个节点(除了跟) 都恰好有一条边线上连接到另外一个节点,上面的这个节点就是下面的这个节点的父节点

子节点:每个节点 都可能有一条边线下连接到另外一个节点,下面的这个节点就是上面的这个节点的子节点

叶节点:没有子节点的节点称为叶节点

子树:每个节点都可以作为"子树"根,它和它多有的子孙节点都含在子树中

二叉树是非平衡树,树中每个节点下面,最多有两个子节点,他的每一个节点,左子节点比该节点小,右子节点比该节点大.

二叉树的查找:速度是非常快的

二叉树的插入:插入节点和当前节点比较,小放左边,大放右边

二叉树的删除:先找到要删除的节点,
如果该节点有两个子节点,节点删除,右子树最左边的节点代替原来删除的节点
如果该节点只有左子节点,节点删除,左子节点代替原来删除的节点
如果该节点只有右子节点,节点删除,右子节点代替原来删除的节点
如果该节点没有子节点,直接删除.


package com.test.tree;


import java.util.Stack;  

public class BinaryTree {  
  private Node root;  
  public BinaryTree(){  
      root = null;  
  }  
    
  public void insert(int iData,double dData){  
      Node newNode = new Node();  
      newNode.setiData(iData);  
      newNode.setdData(dData);  
      if(root == null){//空树  
          root = newNode;  
      }else{  
          Node current = root;  
          Node parent;  
          while(true){  
              parent = current;  
              if(iData<current.getiData()){//往左边找  
                  current = current.getLeftChild();  
                  if(current==null){//左边的为空了,插入newNode  
                      parent.setLeftChild(newNode);  
                      return;  
                  }  
              }else{//否则往右边找  
                  current = current.getRightChild();  
                  if(current == null){//右边为空了,插入newNode  
                      parent.setRightChild(newNode);  
                      return;  
                  }  
              }  
          }  
      }  
  }  
    
  public boolean delete(int key){  
      Node current = root;  
      Node parent = root;  
      boolean isLeftChild = true;  
      while(current.getiData() != key){//找到要删除的节点current  
          parent = current;  
          if(key<current.getiData()){  
              isLeftChild = true;  
              current = current.getLeftChild();  
          }else{  
              isLeftChild = false;  
              current = current.getRightChild();  
          }  
          if(current ==null) return false;//没有找到要删除的节点,返回false,删除失败  
      }  
      if(current.getLeftChild() == null && current.getRightChild()==null){//current没有子节点,直接删除  
          if(current ==root)root = null;  
          else if(isLeftChild){  
              parent.setLeftChild(null);  
          }else{  
              parent.setRightChild(null);  
          }  
      }else if(current.getRightChild() == null){//要删除的节点只有左子节点  
          if(current == root ) root = current.getLeftChild();  
          else if(isLeftChild) parent.setLeftChild(current.getLeftChild());  
          else parent.setRightChild(current.getLeftChild());  
      }else if (current.getLeftChild() == null){//要删除的节点只有右节点  
          if(current == root ) root = current.getRightChild();  
          else if(isLeftChild) parent.setLeftChild(current.getRightChild());  
          else parent.setRightChild(current.getRightChild());  
      }else{//要删除的节点有两个子节点,current右边子树的最左边的那个节点替换current  
          Node replace = getReplace(current);  
          if(current == root) root = replace;  
          else if(isLeftChild) parent.setLeftChild(replace);  
          else parent.setRightChild(replace);  
          replace.setLeftChild(current.getLeftChild());  
      }  
      return true;  
  }  

  private Node getReplace(Node delNode) {  
      Node replaceParent = delNode;  
      Node replace = delNode;  
      Node current = delNode.getRightChild();  
      while(current != null){//找到要删除节点右边子树的最左边的那个节点  
          replaceParent = replace;  
          replace = current;  
          current = current.getLeftChild();  
      }  
      if(replace != delNode.getRightChild()){  
          replaceParent.setLeftChild(replace.getRightChild());  
          replace.setRightChild(delNode.getRightChild());  
      }  
      return replace;  
  }  
    
  public Node find(int key){  
      Node current = root;  
      while(current.getiData() != key){  
          if(key<current.getiData()){  
              current = current.getLeftChild();  
          }else{  
              current = current.getRightChild();  
          }  
          if(current == null) return null;  
      }  
      return current;  
  }  
    
  public void traverses(int traverseType){//从左到右,从下到上  
      switch(traverseType){  
      case 1://从上至下,从左到右  
          System.out.println("\n Preorder traversal:");  
          preOrder(root); 
          System.out.println();
          break;  
      case 2://从下至上,从左到右  
          System.out.println("\n Inorder traversal:");  
          inOrder(root); 
          System.out.println();
          break;  
      case 3://从下至上,从右到左  
          System.out.println("\n Postorder traversal:");  
          postOrder(root); 
          System.out.println();
          break;  
      }  
  }  

  private void postOrder(Node localRoot) {//从下至上,从右到左  
      if(localRoot!=null){  
          postOrder(localRoot.getRightChild());  
          postOrder(localRoot.getLeftChild());  
          System.out.print(localRoot.getiData()+" ");  
      }  
        
  }  

  private void inOrder(Node localRoot) {//从下至上,从左到右  
      if(localRoot != null){  
          inOrder(localRoot.getLeftChild());  
          System.out.print(localRoot.getiData()+" ");  
          inOrder(localRoot.getRightChild());  
      }  
        
  }  

  private void preOrder(Node localRoot) {//从上至下,从左到右  
      if(localRoot!=null){  
          System.out.print(localRoot.getiData()+" ");  
          preOrder(localRoot.getLeftChild());  
          preOrder(localRoot.getRightChild());  
      }  
  }  
    
  public void displayTree(){  
      Stack<Node> globalStack = new Stack<Node>();  
      globalStack.push(root);  
      int nBlanks =32;  
      boolean isRowEmpty = false;  
      System.out.println("----------------------------------------------------------------");  
      while(isRowEmpty == false){  
          Stack<Node> localStack = new Stack<Node>();  
          isRowEmpty = true;  
          for(int j=0;j<nBlanks;j++){  
        	  for(j=0;j<nBlanks-2; j++){  
                  System.out.print(" ");  
              }   
              while(globalStack.isEmpty()==false){  
                  Node temp= (Node)globalStack.pop();  
                  if(temp!=null){  
                      System.out.print(temp.getiData());  
                      localStack.push(temp.getLeftChild());  
                      localStack.push(temp.getRightChild());  
                      if(temp.getLeftChild()!=null || temp.getRightChild()!=null){  
                          isRowEmpty = false;  
                      }  
                  }else{  
                      System.out.print("**");  
                      localStack.push(null);  
                      localStack.push(null);  
                  }  
                  for(j=0;j<nBlanks*2-2; j++){  
                      System.out.print(" ");  
                  }  
              }//while end  
              System.out.println();  
              nBlanks/=2;  
              while(localStack.isEmpty()==false){  
                  globalStack.push(localStack.pop());  
              }  
          }  
          System.out.println(".............................................................");  
      }  
  }  
}  


package com.test.tree;
public class Node {  
    private int iData;  
    private double dData;  
    private Node leftChild;  
    private Node rightChild;  
      
    public void display(){  
        System.out.println(toString());  
    }  
      
      
    /** 
     * @return the iData 
     */  
    public int getiData() {  
        return iData;  
    }  
  
  
    /** 
     * @param iData the iData to set 
     */  
    public void setiData(int iData) {  
        this.iData = iData;  
    }  
  
  
    /** 
     * @return the dData 
     */  
    public double getdData() {  
        return dData;  
    }  
  
  
    /** 
     * @param dData the dData to set 
     */  
    public void setdData(double dData) {  
        this.dData = dData;  
    }  
  
  
  
  
  
    public Node getLeftChild() {
		return leftChild;
	}


	public void setLeftChild(Node leftChild) {
		this.leftChild = leftChild;
	}


	public Node getRightChild() {
		return rightChild;
	}


	public void setRightChild(Node rightChild) {
		this.rightChild = rightChild;
	}


	@Override
	public String toString() {
		return "Node [iData=" + iData + ", dData=" + dData + ", leftChild="
				+ leftChild + ", rightChild=" + rightChild + "]";
	}





package com.test.tree;

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
  
public class BinaryTreeTest {  
      
    public static String getString()throws IOException{  
        InputStreamReader is = new InputStreamReader(System.in);  
        BufferedReader br =  new BufferedReader(is);  
        return br.readLine();  
    }  
      
    public static char getChar()throws IOException{  
        return getString().charAt(0);  
    }  
    public static int getInt()throws IOException{  
        return Integer.parseInt(getString());  
    }  
    /** 
     * @param args 
     * @throws IOException  
     */  
    public static void main(String[] args) throws IOException {  
        int value;  
        BinaryTree t = new BinaryTree();  
        int nodeNumber = 10;
        for(int i=0;i<nodeNumber;i++){
        	int iData = (int)(Math.random()*(100-10)+10);//10-100 random data
        	t.insert(iData, 1.5d);
        }
       
  
        while(true){  
            System.out.print("Enter first letter of show, insert, find,delete or traverse:");  
            char choice = getChar();  
            switch(choice){  
            case 's'://display  
                t.displayTree();  
                break;  
            case 'i'://insert  
                System.out.print("Enter value to insert:");  
                value =  getInt();  
                t.insert(value, 9.9d);  
                break;  
            case 'f'://find  
                System.out.print("Enter value to find:");  
                value =  getInt();  
                Node found = t.find(value);  
                if(found!=null){  
                    System.out.print("found:");  
                    found.display();  
                    System.out.println();  
                }else{  
                    System.out.println("could not find "+value);  
                }  
                break;  
            case 'd'://delete  
                System.out.print("Enter value to delete:");  
                value =  getInt();  
                boolean result = t.delete(value);  
                if(result){  
                    System.out.println("delete successful");  
                }else{  
                    System.out.println("delete failed");  
                }  
                break;  
            case 't':  
                System.out.print("Enter traverse type 1,2 or 3:");  
                value = getInt();  
                t.traverses(value);  
                break;  
            default:  
                System.out.println("Invalid input");  
            }  
        }  
    }  
  
}  

分享到:
评论

相关推荐

    二叉树建立 二叉树基本算法的实现

    (2)先序、中序、后序遍历二叉树:递归算法。 (3)中序遍历二叉树:非递归算法(最好也能实现先序,后序非递归算法)。 (4)求二叉树的高度 。 (5)求二叉树的叶子个数。 (6)对于树中每一个元素值为x的结点...

    二叉树的基本运算

    建立一棵二叉树,试编程实现二叉树的如下基本操作: 1. 按先序序列构造一棵二叉链表表示的二叉树T; 2. 对这棵二叉树进行遍历:先序、中序、后序以及层次遍历,分别输出结点的遍历序列; 3. 求二叉树的深度/结点数目...

    二叉树相关算法的实验验证+判别给定二叉树是否为完全二叉树。

    1、 定义链接存储的二叉树类。 2、 实验验证如下算法的正确性、各种功能及指标: 1) 创建一棵二叉树,并对其初始化; 2)先根、中根、后根遍历二叉树; 3) 在二叉树中搜索给定结点的父结点; 4) 搜索二叉树中符合...

    二叉树的建立与基本操作

    编写程序实现二叉树的如下操作: 1) 建立二叉链表 2) 二叉树的先序、中序、后序遍历 3) 求解二叉树的叶子结点个数 4) 将二叉树中所有结点的左、右子树相互交换 输入:  扩展二叉树先序序列:ab#d##ce###。其中#...

    二叉树_二叉树遍历_

    1.二叉树的基本操作实现【问题描述】建立一棵二叉树,用递归方法实现二叉树的如下基本操作:(1)按先序序列构造一棵二叉链表表示的二叉树T;(2)对这棵二叉树进行遍历:先序、中序、后序以及层次遍历,分别输出...

    二叉树课程设计的实验报告

    3 程序所能达到的功能:生成一个新的二叉树,实现对二叉树的先序,中序,后序和层次遍历,计算二叉树的深度,结点数,叶结点数,。 4 测式数据: A生成一个新的二叉树后,直接在键盘上按要求输入字符,可以依次输入...

    数据结构试验3二叉树建立,遍历等

    数据结构试验3二叉树建立,遍历等操作代码及运行结果。 实验内容: 采用二叉链表存储,实现二叉树的创建、遍历(递归)、赫夫曼编码和译码等典型操作。 1. 编程实现如下功能: (1)假设二叉树的结点值是字符型,...

    二叉树的建立及遍历

    如果给出了遍历二叉树的前序序列和中序序列,则可以构造出唯一的一棵二叉树。试编写实现上述功能的程序。 [基本要求] 已知一棵二叉树的前序和中序序列,试设计完成下列任务的一个算法: (1)构造一棵二叉树...

    数据结构 树和二叉树ppt教程

    详细的树和二叉树的教程,还附有源代码 部分代码如下: 二叉树头文件.h //二叉树的二叉链表存储表示 typedef struct BiTNode {TElemType data; //二叉树结点数据域 struct BiTNode *lchild,*rchild; //左右孩子指针...

    二叉树的建立与遍历

    按先序序列构造一棵二叉链表表示的二叉树T,并输出该T的中序遍历序列。实现提示: 1) 按先序序列建立一棵二叉树时,先构造根结点,再构造根的左子树,然后构造右子树;每棵子树又都是二叉树,所以构造一棵子树的过程...

    根据先序与中序遍历结果建立二叉树

    根据先序与中序遍历结果建立二叉树 输入为: 第一行:二叉树的先序遍历结果 第二行:二叉树的中序遍历结果 例如: ①输入aa则返回的指针指向的二叉树应该就是仅有一个节点,值为a. ②输入123213则返回的指针指向...

    数据结构实验-二叉树的基本操作

    运用二叉链表实现二叉树的基本操作,包括:创建二叉树的存储结构、复制已有的二叉树、计算已有的二叉树的深度、先根序序列、中根序序列、后根序序列等。 输入格式:AB#C##D## 二、实验目的 掌握二叉链表及二叉树的...

    数据结构实验——二叉树的建立和遍历.zip

    1.采用二叉链表作为存储结构,创建一棵二叉树; 2.用递归及非递归算法对二叉树实现先序遍历; 3.用递归及非递归算法对二叉树实现中序遍历; 4.用递归及非递归算法对二叉树实现后序遍历。 5.用递归遍历算法中的访问...

    数据结构——二叉树有关操作程序

    一)建立二叉树+判空+遍历 (1)以二叉链表作为存储结构,从键盘以先序次序输入各个结点(空格字符表示空树)建立一棵二叉树; (2)对(1)中生成的二叉树进行判空; (3)对(1)中生成的二叉树进行遍历(分别实现...

    二叉树---数据结构

    二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树二叉树

    数据结构实验 二叉树的遍历方法

    一、实验名称:二叉树的遍历方法 二、实验目的: (1)熟悉C语言的上机环境,进一步掌握C语言的结构特点; (2)掌握二叉树的储存结构的定义及C语言实现; (3)掌握二叉树的三种遍历方法,即先序遍历,中序遍历,...

    C++ 数据库二叉树的实现

    4.掌握计算二叉树的结点个数、二叉树的深度、二叉树的叶子结点和二叉树复制算法。 二、实验内容 1、构造基于先序遍历的二叉链表。 要求:按先序遍历规则,从键盘连续输入二叉树的先序序列,若无孩子结点,则用#代替...

    数据结构二叉树实验头文件

    在计算机科学中,二叉树是每个结点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。二叉树常被用于实现二叉查找树和二叉堆。 一棵深度为k,且有2^k-1个结点的...

    北京邮电大学_信通院_数据结构_二叉树 C++

    根据二叉树的抽象数据类型的定义,使用二叉链表实现一个二叉树。 二叉树的基本功能: 1、二叉树的建立 2、前序遍历二叉树 3、中序遍历二叉树 4、后序遍历二叉树 5、按层序遍历二叉树 6、求二叉树的深度 7、求指定...

Global site tag (gtag.js) - Google Analytics