码迷,mamicode.com
首页 > 编程语言 > 详细

java二叉排序树

时间:2016-05-23 17:24:25      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:

  二叉排序树又称二叉查找树。它或者是一颗空树,或者是具有如下性质的二叉树:

  1.如果左子树不空,那么左子树上的所有节点均小于它的根节点的值;

  2.如果右子树不空,那么右子树上的所有节点均大于它的根节点的值;

  3.左右字树也分别是二叉排序树。

  关于二叉排序树的建立和遍历的代码实现如下:

 1 class Node{
 2     public int data;
 3     public Node left;
 4     public Node right;
 5     public Node(int data){
 6         this.data = data;
 7         this.left = null;
 8         this.right = null;
 9     }
10 }
11 
12 public class BinaryTree{
13     
14     private Node root;
15     public BinaryTree(){
16         root = null;
17     }
18 
19     //将date插入到排序二叉树中
20     public void insert(int data){
21         Node newNode = new Node(data);
22         if(root == null)
23             root = newNode;
24         else{
25             Node current = root;
26             Node parent;
27             while (true) {    //寻找插入的位置
28                 parent = current;
29                 if(data<current.data){
30                     current = current.left;
31                     if(current == null){
32                         parent.left = newNode;
33                         return;
34                     }
35                 }
36                 else{
37                     current = current.right;
38                     if(current == null){
39                         parent.right = newNode;
40                         return;
41                     }
42                 }
43             }
44         }
45     }
46     //输入数值,构建二叉树
47     public void buildTree(int[] data){
48         for (int i=0; i<data.length; i++) {
49             insert(data[i]);
50         }
51     }
52     //中序遍历方法递归实现
53     public void inOrder(Node localRoot){
54         if (localRoot !=null) {
55             inOrder(localRoot.left);
56             System.out.print(localRoot.data+" ");
57             inOrder(localRoot.right);
58         }
59     }
60     public void inOrder(){
61         this.inOrder(this.root);
62     }
63     //先序遍历方法递归实现
64     public void preOrder(Node localRoot){
65         if (localRoot !=null) {
66             System.out.print(localRoot.data+" ");
67             preOrder(localRoot.left);
68             preOrder(localRoot.right);
69         }
70     }
71     public void preOrder(){
72         this.preOrder(this.root);
73     }
74     //后序遍历方法递归实现
75     public void postOrder(Node localRoot){
76         if (localRoot !=null) {
77             postOrder(localRoot.left);
78             postOrder(localRoot.right);
79             System.out.print(localRoot.data+" ");
80         }
81     }
82     public void postOrder(){
83         this.postOrder(this.root);
84     }
85     
86 }

 

java二叉排序树

标签:

原文地址:http://www.cnblogs.com/Eason-S/p/5520433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!