首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Java中创建使用二叉搜索树获取前一个节点的方法?

在Java中创建使用二叉搜索树获取前一个节点的方法可以通过以下步骤实现:

  1. 首先,创建一个二叉搜索树的节点类,包含节点值、左子节点和右子节点的引用。
代码语言:txt
复制
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
  1. 创建一个二叉搜索树类,包含根节点的引用和相应的操作方法。
代码语言:txt
复制
class BinarySearchTree {
    private TreeNode root;

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

    // 插入节点
    public void insert(int val) {
        root = insertNode(root, val);
    }

    private TreeNode insertNode(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }

        if (val < root.val) {
            root.left = insertNode(root.left, val);
        } else if (val > root.val) {
            root.right = insertNode(root.right, val);
        }

        return root;
    }

    // 获取前一个节点
    public TreeNode getPredecessor(TreeNode node) {
        if (node == null) {
            return null;
        }

        // 如果节点有左子节点,则前一个节点为左子树中的最右节点
        if (node.left != null) {
            TreeNode predecessor = node.left;
            while (predecessor.right != null) {
                predecessor = predecessor.right;
            }
            return predecessor;
        }

        // 如果节点没有左子节点,则前一个节点为其父节点或祖先节点中第一个比它大的节点
        TreeNode predecessor = null;
        TreeNode current = root;
        while (current != null) {
            if (node.val > current.val) {
                predecessor = current;
                current = current.right;
            } else if (node.val < current.val) {
                current = current.left;
            } else {
                break;
            }
        }
        return predecessor;
    }
}
  1. 使用二叉搜索树类进行测试。
代码语言:txt
复制
public class Main {
    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();
        bst.insert(5);
        bst.insert(3);
        bst.insert(7);
        bst.insert(2);
        bst.insert(4);
        bst.insert(6);
        bst.insert(8);

        TreeNode node = bst.getPredecessor(bst.root.right.right);
        if (node != null) {
            System.out.println("前一个节点的值为:" + node.val);
        } else {
            System.out.println("该节点没有前一个节点");
        }
    }
}

以上代码演示了如何在Java中创建使用二叉搜索树获取前一个节点的方法。在二叉搜索树中,如果节点有左子节点,则前一个节点为左子树中的最右节点;如果节点没有左子节点,则前一个节点为其父节点或祖先节点中第一个比它大的节点。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券