Java:实现Lowest Common Ancestor最近公共祖先算法(附完整源码)

本文提供了一篇原创的Java实现最近公共祖先(LCA)算法的详细教程,通过深度优先搜索策略解决数据结构问题。文章附带完整的源代码,适合对算法和数据结构感兴趣的Java开发者学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java:实现Lowest Common Ancestor最近公共祖先算法

package com.williamfiset.algorithms.graphtheory.treealgorithms;

import java.util.*;

public class LowestCommonAncestor 
请检查下述代码错误:#include<iostream> using namespace std; struct BiNode//结点定义 { int data; BiNode* lchild, * rchild; }; class BiSortTree { public: BiSortTree(int a[], int n);//建立a[n]的二叉排序树 ~BiSortTree() { Release(root); } BiNode* InsertBST(int x) { return InsertBST(root, x); }//插入记录 BiNode* lowestCommonAncestor(BiNode* p, BiNode* q) { return lowestCommonAncestor(root, p, q); } BiNode* SearchBST(int k) { return SearchBST(root, k); } private: BiNode* InsertBST(BiNode* bt, int x); void Release(BiNode* bt); BiNode* SearchBST(BiNode* bt, int k); BiNode* lowestCommonAncestor(BiNode* root, BiNode* p, BiNode* q); BiNode* root; }; BiSortTree::BiSortTree(int a[], int n) { root = nullptr; for (int i = 0; i < n; i++) root = InsertBST(root, a[i]); } BiNode* BiSortTree::lowestCommonAncestor(BiNode* root, BiNode* p, BiNode* q) { if (!root) return NULL; // 如果根节点为空,返回NULL if (root->data > p->data && root->data > q->data) { return lowestCommonAncestor(root->lchild, p, q); // 如果根节点大于p和q的值,那么p和q在根节点的左子树中,递归左子树 } else if (root->data < p->data && root->data < q->data) { return lowestCommonAncestor(root->rchild, p, q); // 如果根节点小于p和q的值,那么p和q在根节点的右子树中,递归右子树 } else { return root; // 如果根节点的值介于p和q的值之间,那么根节点就是它们的最近公共祖先 } } BiNode* BiSortTree::InsertBST(BiNode* bt, int x) { if (bt == nullptr) { //找到插入位置 BiNode* s = new BiNode; s->data = x; s->lchild = nullptr; s->rchild = nullptr; bt = s; return bt; } else if (bt->data > x) bt->lchild = InsertBST(bt->lchild, x); else bt->rchild = InsertBST(bt->rchild, x); } void BiSortTree::Release(BiNode* bt) { if (bt == nullptr) return; else { Release(bt->lchild); //释放左子树 Release(bt->rchild); //释放右子树 delete bt; //释放根结点 } } BiNode* BiSortTree::SearchBST(BiNode* bt, int k) { if (bt == nullptr) return nullptr; if (bt->data == k) return bt; else if (bt->data > k) return SearchBST(bt->lchild, k); else return SearchBST(bt->rchild, k); } int main() { int a[] = { 63,90,70,55,67,42,98 }; BiSortTree T{ a, 7 }; cout << T.lowestCommonAncestor(T.SearchBST(42), T.SearchBST(55))->data;
06-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源代码大师

赏点狗粮吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值