Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 298|回复: 0

[算法学习]二叉搜索树的操作

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-29 23:59:28 | 显示全部楼层 |阅读模式
    1. 一、节点类
    2. import java.io.*;
    3. import java.util.*;            // for Stack class
    4. class Node
    5.    {
    6.    public int iData;           // data item (key)
    7.    public double dData;       // data item
    8.    public Node leftChild;    // this node"s left child
    9.    public Node rightChild;   // this node"s right child
    10.    public void displayNode()  // display ourself
    11.       {
    12.       System.out.print("{");
    13.       System.out.print(iData);
    14.       System.out.print(", ");
    15.       System.out.print(dData);
    16.       System.out.print("} ");
    17.       }
    18.    }  // end class Node
    复制代码

       
      
      二、二叉搜索树

    1. class Tree
    2.    {
    3.    private Node root;             // first node of tree
    4. // -------------------------------------------------------------
    5.    public Tree()                  // constructor
    6.       { root = null; }            // no nodes in tree yet
    7. // -------------------------------------------------------------
    8.    public Node find(int key)      // find node with given key
    9.       {                           // (assumes non-empty tree)
    10.       Node current = root;               // start at root
    11.       while(current.iData != key)        // while no match,
    12.          {
    13.          if(key < current.iData)         // go left?
    14.             current = current.leftChild;
    15.          else                            // or go right?
    16.             current = current.rightChild;
    17.          if(current == null)             // if no child,
    18.             return null;                 // didn"t find it
    19.          }
    20.       return current;                    // found it
    21.       }  // end find()
    22. // -------------------------------------------------------------
    23.    public void insert(int id, double dd)
    24.       {
    25.       Node newNode = new Node();    // make new node
    26.       newNode.iData = id;           // insert data
    27.       newNode.dData = dd;
    28.       if(root==null)                // no node in root
    29.          root = newNode;
    30.       else                          // root occupied
    31.          {
    32.          Node current = root;       // start at root
    33.          Node parent;
    34.          while(true)                // (exits internally)
    35.             {
    36.             parent = current;
    37.             if(id < current.iData)  // go left?
    38.                {
    39.                current = current.leftChild;
    40.                if(current == null)  // if end of the line,
    41.                   {                 // insert on left
    42.                   parent.leftChild = newNode;
    43.                   return;
    44.                   }
    45.                }  // end if go left
    46.             else                    // or go right?
    47.                {
    48.                current = current.rightChild;
    49.                if(current == null)  // if end of the line
    50.                   {                 // insert on right
    51.                   parent.rightChild = newNode;
    52.                   return;
    53.                   }
    54.                }  // end else go right
    55.             }  // end while
    56.          }  // end else not root
    57.       }  // end insert()
    58. // -------------------------------------------------------------
    59.    public boolean delete(int key) // delete node with given key
    60.       {                           // (assumes non-empty list)
    61.       Node current = root;
    62.       Node parent = root;
    63.       boolean isLeftChild = true;
    64.       while(current.iData != key)        // search for node
    65.          {
    66.          parent = current;
    67.          if(key < current.iData)         // go left?
    68.             {
    69.             isLeftChild = true;
    70.             current = current.leftChild;
    71.             }
    72.          else                            // or go right?
    73.             {
    74.             isLeftChild = false;
    75.             current = current.rightChild;
    76.             }
    77.          if(current == null)             // end of the line,
    78.             return false;                // didn"t find it
    79.          }  // end while
    80.       // found node to delete
    81.       // if no children, simply delete it
    82.       if(current.leftChild==null &&
    83.                                    current.rightChild==null)
    84.          {
    85.          if(current == root)             // if root,
    86.             root = null;                 // tree is empty
    87.          else if(isLeftChild)
    88.             parent.leftChild = null;     // disconnect
    89.          else                            // from parent
    90.             parent.rightChild = null;
    91.          }
    92.       // if no right child, replace with left subtree
    93.       else if(current.rightChild==null)
    94.          if(current == root)
    95.             root = current.leftChild;
    96.          else if(isLeftChild)
    97.             parent.leftChild = current.leftChild;
    98.          else
    99.             parent.rightChild = current.leftChild;
    100.       // if no left child, replace with right subtree
    101.       else if(current.leftChild==null)
    102.          if(current == root)
    103.             root = current.rightChild;
    104.          else if(isLeftChild)
    105.             parent.leftChild = current.rightChild;
    106.          else
    107.             parent.rightChild = current.rightChild;
    108.       else  // two children, so replace with inorder successor
    109.          {
    110.          // get successor of node to delete (current)
    111.          Node successor = getSuccessor(current);
    112.          // connect parent of current to successor instead
    113.          if(current == root)
    114.             root = successor;
    115.          else if(isLeftChild)
    116.             parent.leftChild = successor;
    117.          else
    118.             parent.rightChild = successor;
    119.          // connect successor to current"s left child
    120.          successor.leftChild = current.leftChild;
    121.          }  // end else two children
    122.       // (successor cannot have a left child)
    123.       return true;                                // success
    124.       }  // end delete()
    125. // -------------------------------------------------------------
    126.    // returns node with next-highest value after delNode
    127.    // goes to right child, then right child"s left descendents
    128.    private Node getSuccessor(Node delNode)
    129.       {
    130.       Node successorParent = delNode;
    131.       Node successor = delNode;
    132.       Node current = delNode.rightChild;   // go to right child
    133.       while(current != null)               // until no more
    134.          {                                 // left children,
    135.          successorParent = successor;
    136.          successor = current;
    137.          current = current.leftChild;      // go to left child
    138.          }
    139.                                            // if successor not
    140.       if(successor != delNode.rightChild)  // right child,
    141.          {                                 // make connections
    142.          successorParent.leftChild = successor.rightChild;
    143.          successor.rightChild = delNode.rightChild;
    144.          }
    145.       return successor;
    146.       }
    147. // -------------------------------------------------------------
    148.    public void traverse(int traverseType)
    149.       {
    150.       switch(traverseType)
    151.          {
    152.          case 1: System.out.print("
    153. Preorder traversal: ");
    154.                  preOrder(root);
    155.                  break;
    156.          case 2: System.out.print("
    157. Inorder traversal:  ");
    158.                  inOrder(root);
    159.                  break;
    160.          case 3: System.out.print("
    161. Postorder traversal: ");
    162.                  postOrder(root);
    163.                  break;
    164.          }
    165.       System.out.println();
    166.       }
    167. // -------------------------------------------------------------
    168.    private void preOrder(Node localRoot)
    169.       {
    170.       if(localRoot != null)
    171.          {
    172.          System.out.print(localRoot.iData + " ");
    173.          preOrder(localRoot.leftChild);
    174.          preOrder(localRoot.rightChild);
    175.          }
    176.       }
    177. // -------------------------------------------------------------
    178.    private void inOrder(Node localRoot)
    179.       {
    180.       if(localRoot != null)
    181.          {
    182.          inOrder(localRoot.leftChild);
    183.          System.out.print(localRoot.iData + " ");
    184.          inOrder(localRoot.rightChild);
    185.          }
    186.       }
    187. // -------------------------------------------------------------
    188.    private void postOrder(Node localRoot)
    189.       {
    190.       if(localRoot != null)
    191.          {
    192.          postOrder(localRoot.leftChild);
    193.          postOrder(localRoot.rightChild);
    194.          System.out.print(localRoot.iData + " ");
    195.          }
    196.       }
    197. // -------------------------------------------------------------
    198.    public void displayTree()
    199.       {
    200.       Stack globalStack = new Stack();
    201.       globalStack.push(root);
    202.       int nBlanks = 32;
    203.       boolean isRowEmpty = false;
    204.       System.out.println(
    205.       "......................................................");
    206.       while(isRowEmpty==false)
    207.          {
    208.          Stack localStack = new Stack();
    209.          isRowEmpty = true;
    210.          for(int j=0; j< nBlanks; j++)
    211.             System.out.print(" ");
    212.          while(globalStack.isEmpty()==false)
    213.             {
    214.             Node temp = (Node)globalStack.pop();
    215.             if(temp != null)
    216.                {
    217.                System.out.print(temp.iData);
    218.                localStack.push(temp.leftChild);
    219.                localStack.push(temp.rightChild);
    220.                if(temp.leftChild != null ||
    221.                                    temp.rightChild != null)
    222.                   isRowEmpty = false;
    223.                }
    224.             else
    225.                {
    226.                System.out.print("--");
    227.                localStack.push(null);
    228.                localStack.push(null);
    229.                }
    230.             for(int j=0; j< nBlanks*2-2; j++)
    231.                System.out.print(" ");
    232.             }  // end while globalStack not empty
    233.          System.out.println();
    234.          nBlanks /= 2;
    235.          while(localStack.isEmpty()==false)
    236.             globalStack.push( localStack.pop() );
    237.          }  // end while isRowEmpty is false
    238.       System.out.println(
    239.       "......................................................");
    240.       }  // end displayTree()
    241. // -------------------------------------------------------------
    242.    }  // end class Tree
    243. ////////////////////////////////////////////////////////////////
    244. class TreeApp
    245.    {
    246.    public static void main(String[] args) throws IOException
    247.       {
    248.       int value;
    249.       Tree theTree = new Tree();
    250.       theTree.insert(50, 1.5);
    251.       theTree.insert(25, 1.2);
    252.       theTree.insert(75, 1.7);
    253.       theTree.insert(12, 1.5);
    254.       theTree.insert(37, 1.2);
    255.       theTree.insert(43, 1.7);
    256.       theTree.insert(30, 1.5);
    257.       theTree.insert(33, 1.2);
    258.       theTree.insert(87, 1.7);
    259.       theTree.insert(93, 1.5);
    260.       theTree.insert(97, 1.5);
    261.       while(true)
    262.          {
    263.          System.out.print("Enter first letter of show, ");
    264.          System.out.print("insert, find, delete, or traverse: ");
    265.          int choice = getChar();
    266.          switch(choice)
    267.             {
    268.             case "s":
    269.                theTree.displayTree();
    270.                break;
    271.             case "i":
    272.                System.out.print("Enter value to insert: ");
    273.                value = getInt();
    274.                theTree.insert(value, value + 0.9);
    275.                break;
    276.             case "f":
    277.                System.out.print("Enter value to find: ");
    278.                value = getInt();
    279.                Node found = theTree.find(value);
    280.                if(found != null)
    281.                   {
    282.                   System.out.print("Found: ");
    283.                   found.displayNode();
    284.                   System.out.print("
    285. ");
    286.                   }
    287.                else
    288.                   System.out.print("Could not find ");
    289.                   System.out.print(value + "
    290. ");
    291.                break;
    292.             case "d":
    293.                System.out.print("Enter value to delete: ");
    294.                value = getInt();
    295.                boolean didDelete = theTree.delete(value);
    296.                if(didDelete)
    297.                   System.out.print("Deleted " + value + "
    298. ");
    299.                else
    300.                   System.out.print("Could not delete ");
    301.                   System.out.print(value + "
    302. ");
    303.                break;
    304.             case "t":
    305.                System.out.print("Enter type 1, 2 or 3: ");
    306.                value = getInt();
    307.                theTree.traverse(value);
    308.                break;
    309.             default:
    310.                System.out.print("Invalid entry
    311. ");
    312.             }  // end switch
    313.          }  // end while
    314.       }  // end main()
    315. // -------------------------------------------------------------
    316.    public static String getString() throws IOException
    317.       {
    318.       InputStreamReader isr = new InputStreamReader(System.in);
    319.       BufferedReader br = new BufferedReader(isr);
    320.       String s = br.readLine();
    321.       return s;
    322.       }
    323. // -------------------------------------------------------------
    324.    public static char getChar() throws IOException
    325.       {
    326.       String s = getString();
    327.       return s.charAt(0);
    328.       }
    329. //-------------------------------------------------------------
    330.    public static int getInt() throws IOException
    331.       {
    332.       String s = getString();
    333.       return Integer.parseInt(s);
    334.       }
    335. // -------------------------------------------------------------
    336.    }  // end class TreeApp
    337. ////////////////////////////////////////////////////////////////
    复制代码
    三、运行
    1. C:java>java  TreeApp
    2. Enter first letter of show, insert, find, delete, or traverse: s
    3. ......................................................
    4.                                 50
    5.                 25                              75
    6.         12              37              --              87
    7.     --      --      30      43      --      --      --      93
    8.   --  --  --  --  --  33  --  --  --  --  --  --  --  --  --  97
    9. ......................................................
    10. Enter first letter of show, insert, find, delete, or traverse: t
    11. Enter type 1, 2 or 3: 1
    12. Preorder traversal: 50 25 12 37 30 33 43 75 87 93 97
    13. Enter first letter of show, insert, find, delete, or traverse: d
    14. Enter value to delete: 87
    15. Deleted 87
    16. 97Enter first letter of show, insert, find, delete, or traverse: s
    17. ......................................................
    18.                                 50
    19.                 25                              75
    20.         12              37              --              93
    21.     --      --      30      43      --      --      --      97
    22.   --  --  --  --  --  33  --  --  --  --  --  --  --  --  --  --
    23. ......................................................
    24. Enter first letter of show, insert, find, delete, or traverse:
    复制代码


      
      
       
       

         
       

         
       
      
      
      

      










    源码下载:http://file.javaxxz.com/2014/10/29/235928234.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-5 12:58 , Processed in 0.411866 second(s), 34 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表