二叉搜索树寻找最近公共节点

节点类
@Data
public class Node {
    private int value;
    private Node left;
    private Node right;

    public Node() {
    }

    public Node(Node left, Node right, int value) {
        this.left = left;
        this.right = right;
        this.value = value;
    }
    
    public Node(int value){
        this.value=value;
    }
}

二叉搜索树实现

public class BinarySortTree {
    private Node root = null;
    //构造二叉搜索树
    public void insertBST(int key) {
        Node p = root;
        Node prev = null; //查找节点的前一个节点
        while (p != null) {
            prev = p;
            if (key < p.getValue())
                p = p.getLeft();
            else if (key > p.getValue())
                p = p.getRight();
            else
                return;
        }
        if (root == null)
            root = new Node(key);
        else if (key < prev.getValue())
            prev.setLeft(new Node(key));
        else prev.setRight(new Node(key));
    }
    /**
     * 中序遍历
     */
    public void nrInOrderTraverse() {
        Stack<Node> stack = new Stack<Node>();
        Node node = root;
        while (node != null || !stack.isEmpty()) {
            while (node != null) {
                stack.push(node);
                node = node.getLeft();
            }
            node = stack.pop();
            System.out.println(node.getValue());
            node = node.getRight();
        }
    }

    //找最近公共节点
    public Node lowestCommonAncestor(Node root, Node p, Node q) {
        while (root != null && root.getValue() != -1) {
            if (root.getValue() > p.getValue() && root.getValue() > q.getValue()) {
                //都比根节点值小,去根节点的左子树继续找
                root = root.getLeft();
            } else if (root.getValue() < p.getValue() && root.getValue() < q.getValue()) {
                //都比根节点值大,去根节点的右子树继续找
                root = root.getRight();
            } else {
                //根节点的值大于p而小于q,说明此时的根节点即为最近公共祖先。
                return root;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        BinarySortTree bst = new BinarySortTree();
        int[] num = {45, 12, 37, + 24, 3, 53, 100, 61, 55, 90, 78};
        Scanner scan = new Scanner(System.in);
        for (int i = 0; i < num.length; i++) {
            bst.insertBST(num[i]);
        }

        Node node1 = new Node(null, null, 3);
        Node node2 = new Node(null, null, 37);
        bst.nrInOrderTraverse();
        System.out.println("------------");
        Node node = bst.lowestCommonAncestor(bst.root, node1, node2);
        System.out.println("最近公共节点为:" + node.getValue());

    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值