二叉搜索树的基础操作(Java)

 1 //1 二叉搜索树的判定
 2 //method 1 利用中序遍历(最优解) 对于任一结点 若它后一个结点的值大于它的值 则为二叉搜索树
 3 //时间复杂度: O(n) 空间复杂度: O(1)
 4 public boolean isBST(BiTNode node)
 5 {
 6     if(node == null)
 7       return true;
 8 
 9     //中序遍历
10     if(!isBST(node.lchild))
11       return false;
12     if(pre != null && node.data <= pre.data)
13       return false;
14     pre = node;
15     if(!isBST(node.rchild))
16       return false;
17     return true;
18 }
19 
20 //method 2 对于任一结点 若其左右子树均为二叉搜索树且其值大于左子树的最大值 小于右子树的最小值 则为二叉搜索树
21 //效率低于第1种方法
22 public boolean isBST(BiTNode node)
23 {
24     if(node == null)
25       return true;
26 
27     if(!isBST(node.lchild) || !isBST(node.rchild))
28       return false;
29     if(node.lchild != null && node.data <= getMaxElement(node.lchild))
30       return false;
31     if(node.rchild != null && node.data >= getMinElement(node.rchild))
32       return false;
33     return true;
34 }
35 
36 //错误方法
37 //该方法只能判定局部二叉树 区别于方法2
38 public boolean isBST(BiTNode node) 
39 {
40     if(node == null)
41         return true;
42         
43     if(!isBST(node.lchild) || !isBST(node.rchild))
44         return false;
45     if(node.rchild != null && node.rchild.data <= node.data)
46         return false;
47     if(node.lchild != null && node.lchild.data >= node.data)
48         return false;
49     return true;
50 }
 1 //2 查找最大元素
 2 //递归
 3 public int getMaxElement(BiTNode node)
 4 {
 5     if(node.rchild == null)
 6       return node.data;
 7         
 8     return getMaxElement(node.rchild);
 9 }
10 
11 //迭代
12 public int findElement(int k, BiTNode node)
13 {
14     if(node == null)
15       return -1; // 查找失败
16 
17     if(k > node.data)
18       return findElement(k, node.rchild);
19     else if(k < node.data)
20       return findElement(k, node.lchild);
21     else
22       return node.data;
23 }
 1 //3 查找给定元素
 2 //递归
 3 public int findElement(int k, BiTNode node)
 4 {
 5     if(node == null)
 6       return -1; // 查找失败
 7 
 8     if(k > node.data)
 9       return findElement(k, node.rchild);
10     else if(k < node.data)
11       return findElement(k, node.lchild);
12     else
13       return node.data;
14 }
15 
16 //迭代
17 public int findElement(int k)
18 {
19     BiTNode p = this.root;
20     
21     while(p != null && p.data != k)
22     {
23       if(k > p.data)
24           p = p.rchild;
25       else if(k < p.data)
26           p = p.lchild;
27     }
28     if(p == null)
29       return -1;
30     else
31       return p.data;
32     //简洁形式
33   //return p == null ? -1 : p.data;
34 }

 

转载于:https://www.cnblogs.com/Huayra/p/10809551.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值