【java学习之路】(数据结构篇)004.递归和二叉搜索树

这篇博客探讨了递归的概念及其在求解数学问题(如求1-100的和)和链表操作(如删除节点)中的应用。接着介绍了二分搜索树的基础,包括其高效性和树结构的重要性。文章详细展示了如何用Java实现二分搜索树的插入、查找、中序遍历等操作,并提供了层序遍历的实现。此外,还讲解了如何找到二分搜索树中的最小节点。
摘要由CSDN通过智能技术生成

递归

递归的概念

递归的方式求1-100的和

public class DGDemo {
    public static int sum(int n){
        //递归到底的情况
        if(n==1){
            return 1;
        }
        return n+sum(n-1);
    }
    
    public static void main(String[] args) {
        System.out.println("1+2+3+...+100="+sum(100));//5050
    }
}

递归的方式删除链表

//使用递归的方式删除链表
public Node removeDG(T val){
    if(this.isEmpty()){
        return null;
    }
    removeDG(head,val);
}

//递归函数
private Node removeDG(Node head, T val) {
    //递归到底的情况
    if(head==null){
        return null;
    }
    //递归操作
    Node eNode = head;
    Node newHead = head.next;
    if(eNode.val==val){
        return newHead;
    }else {
        eNode.next = removeDG(newHead,val);
        return eNode;
    }

练习(剑指offer022)

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null){
            return null;
        }
        int n=0;
        ListNode curNode = head;
        while (curNode!=null){
            n++;
            curNode = curNode.next;
        }
        int index = n-k;
        if(index<0){
            return null;
        }

        curNode = head;
        for(int i=0;i<index;i++){
            curNode = curNode.next;
        }
        return curNode;
    }
}

通过截图

二分搜索树

为什么要有树结构

  • 树结构本身是一种天然的组织结构
  • 高效

二分搜索树的基础

二叉搜索树各种功能实现

package subject.lesson04;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二分搜索树
 */
public class BinarySearch<T extends Comparable<T>> {

    //定义节点的结构
    class Node{
        T val;
        Node left;
        Node right;

        public Node(T val){
            this.val = val;
            this.left = this.right = null;
        }
    }

    //定义根节点
    private Node root;

    public BinarySearch(){
        this.root = null;
    }

    //判断树是否为空
    public boolean isEmpty(){
        return this.root == null;
    }

    //向树中添加节点
    public void add(T ele){
        //使用递归的方式添加节点
        root = add(root,ele);
    }

    private Node add(Node root, T ele) {
        //递归到底
        if(root == null){
            Node node = new Node(ele);
            return node;
        }
        //递归操作
        if(ele.compareTo(root.val)>0){
            root.right = add(root.right,ele);
        }else {
            root.left = add(root.left, ele);
        }
        return root;
    }

    //从树中查找节点
    public Node contains(T ele){
        return contains(root,ele);
    }

    private Node contains(Node root, T ele) {
        //递归到底
        if(root==null){
            return null;
        }
        //递归操作
        T val = root.val;
        if(ele.compareTo(val)==0){
            return root;
        }else if(ele.compareTo(val)>0){
            return contains(root.right,ele);
        }else {
            return contains(root.left,ele);
        }
    }

    //中序遍历
    public List<T> middleOrder(){
        List<T> result = new ArrayList<>();
        middleOrder(root,result);
        return result;
    }

    private void middleOrder(Node root, List<T> result) {
        //递归到底
        if(root==null){
            return;
        }
        //递归方法
        middleOrder(root.left,result);
        result.add(root.val);
        middleOrder(root.right,result);
    }

    //前序遍历
    public List<T> preOrder(){
        List<T> result = new ArrayList<>();
        middleOrder(root,result);
        return result;
    }

    private void preOrder(Node root, List<T> result) {
        //递归到底
        if(root==null){
            return;
        }
        //递归方法
        result.add(root.val);
        middleOrder(root.left,result);
        middleOrder(root.right,result);
    }

    //后序遍历
    public List<T> subOrder(){
        List<T> result = new ArrayList<>();
        middleOrder(root,result);
        return result;
    }

    private void subOrder(Node root, List<T> result) {
        //递归到底
        if(root==null){
            return;
        }
        //递归方法
        middleOrder(root.left,result);
        middleOrder(root.right,result);
        result.add(root.val);
    }

    //层序遍历(广度优先)
    public List<T> laterOrder(){
        List<T> list = new ArrayList<>();
        if(root!=null){
            Queue<Node> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()){
                //从队列中取出队首元素
                Node node = queue.poll();
                list.add(node.val);
                if(node.left!=null){
                    queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
            }
        }
        return list;
    }
    
    //查找最小节点
    public Node findMinNode(){
        if(root ==null){
            return null;
        }
        Node curNode = root;
        while (curNode.left!=null){
            curNode = curNode.left;
        }
        return curNode;
    }
}
return list;
    }
    
    //查找最小节点
    public Node findMinNode(){
        if(root ==null){
            return null;
        }
        Node curNode = root;
        while (curNode.left!=null){
            curNode = curNode.left;
        }
        return curNode;
    }
}
### Java二叉搜索树数据结构 #### 1. 定义与特性 二叉搜索树(Binary Search Tree, BST),亦称为二叉排序树,在Java编程环境中具有重要地位。这种特定类型的二叉树拥有如下属性:对于任意节点而言,其左子树上的所有键值均小于该节点的键值;同理,右子树上的所有键值皆大于此节点的键值;并且左右子树同样遵循上述规则[^3]。 #### 2. 基本操作实现 为了更好地理解如何在Java中构建并运用二叉搜索树,下面给出了一段用于创建BST类及其核心功能——查找方法的具体代码实例: ```java class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } public class BinarySearchTree { private Node root; // 插入新节点的方法 void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int key) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(key); return root; } /* Otherwise, recur down the tree */ if (key < root.key) root.left = insertRec(root.left, key); else if (key > root.key) root.right = insertRec(root.right, key); /* Return the unchanged root pointer */ return root; } boolean search(int key) { return searchRec(root, key); } // Recursive method for searching keys within the binary search tree. boolean searchRec(Node root, int key) { // Base cases: root is null or key is present at root if (root==null || root.key==key) return root != null; // Key is greater than root's key if (root.key < key) return searchRec(root.right,key); // Key is smaller than root's key return searchRec(root.left,key); } } ``` 这段代码展示了怎样定义一个简单的`Node`类来表示单个节点,并通过递归方式实现了向二叉搜索树中插入新元素的功能以及基于比较逻辑执行查找任务的过程[^1]。 #### 3. 应用领域 除了作为基础数据结构外,二叉搜索树还在多个高级应用场景里扮演着不可或缺的角色。例如,在Java集合框架内,像`TreeMap``TreeSet`这样的容器实际上是借助红黑树这一种经过优化后的二叉搜索树形式得以高效运作的。这类改进型二叉搜索树不仅继承了传统BST的优点,还额外引入了一些机制以确保整体高度保持相对较低水平,从而提高了查询效率[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值