首页 > 编程语言 > 详细

二叉排序数(Binary Sort Tree),(BST)

时间:2021-02-20 12:08:51      阅读:40      评论:0      收藏:0      [点我收藏+]

二叉排序数(Binary Sort Tree),BST

1、概念

  • 对于任何一个非叶子结点,它的左子节点均为它小,它的右子结点均比它大

2、树结点

private static class TreeNode{
?
   int val;
   TreeNode left;
   TreeNode right;
?
   public TreeNode(int val) {
       this.val = val;
  }
?
}

3、排序树

public static class BSTree{
?
   // 根结点
   private TreeNode root;
?
}

4、二叉排序树的创建

技术分享图片
// 结点中方法:根据二叉排序树的规则添加结点
public void add(TreeNode newNode){
?
    if (newNode == null){
        return ;
    }
?
    /**
     * 如果当前新结点的值大于当前结点this
     *      如果当前结点右子树为空,直接添加
     *      否则,右子树重新调用add方法,重复此步骤
     */
    if (newNode.val >= this.val){
        if (this.right == null){
            this.right = newNode;
        }else {
            this.right.add(newNode);
        }
    }else {
        if (this.left == null){
            this.left = newNode;
        }else {
            this.left.add(newNode);
        }
    }
}
?
// 树中方法
public void add(TreeNode node){
?
    if(root == null){
        root = node;
    }else {
        root.add(node);
    }
}
?
// 构建二叉搜索树方法
public static BSTree constructBST(int[] array){
?
    if (array.length == 0){
        return null;
    }
?
    // 创建二叉排序树
    BSTree tree = new BSTree();
?
    for (int i = 0; i < array.length; i++) {
        tree.add(new TreeNode(array[i]));
    }
?
    return tree;
?
}
View Code
 

5、二叉排序数的查找(结点)

技术分享图片
// 结点中方法:查找结点,该结点值为val
public TreeNode findNode(int nodeVal){
?
    if (this.val == nodeVal){
        return this;
    }else if (nodeVal < this.val){
        if (this.left == null){
            return null;
        }else {
            return this.left.findNode(nodeVal);
        }
    }else {
        if (this.right == null){
            return null;
        }else {
            return this.right.findNode(nodeVal);
        }
    }
}
?
// 树中方法
public TreeNode find(TreeNode node){
?
    if (node == null){
        return null;
    }else {
        return root.findNode(node.val);
    }
}
View Code
 

6、二叉排序数的查找(父结点)

技术分享图片
// 结点中方法:查找要删除结点的父节点
public TreeNode findFatherNode(int nodeVal){
?
    // 如果当前结点为父节点
    if((this.left != null && this.left.val == nodeVal) ||
       (this.right != null && this.right.val == nodeVal)){
        return this;
    }
    // 如果左子树不为空,并且nodeVal小于当前结点的值
    else if(this.left != null && nodeVal < this.left.val){
        return this.left.findFatherNode(nodeVal);
    }
    // 如果右子树不为空,并且nodeVal大于等于当前结点的值
    else if (this.right != null && nodeVal >= this.right.val){
        return this.right.findFatherNode(nodeVal);
    }
    else {
        return null;
    }
?
}
?
// 树中方法
public TreeNode findParent(TreeNode node){
?
    if (node == null){
        return null;
    }else {
        return root.findFatherNode(node.val);
    }
}
View Code
 



二叉排序数(Binary Sort Tree),(BST)

原文:https://www.cnblogs.com/LittleSkinny/p/14419413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!