全部评论
大佬分享一下代码😂😂
做完奇安信做yy,心累
LCA?
import java.io.*;
import java.util.Scanner;
class BTNode{
public BTNode(int i, BTNode buildTree, BTNode buildTree2) {
this.data=i;
this.left=buildTree;
this.right=buildTree2;
}
int data;
BTNode left,right;
}
public class Main {
static BTNode lca(BTNode root,int l,int r) {
BTNode left=null;
BTNode right=null;
if(l<root.data&&r<root.data) {
left=lca(root.left,l,r);
}else if(l>root.data&&r>root.data) {
right=lca(root.right,l,r);
}else {
return root;
}
if(left==null)
return right;
else if(right==null)
return left;
return root;
}
static void Print(BTNode root,int data) {
if(root!=null) {
if(data==root.data)
f1=true;
Print(root.left,data);
Print(root.right,data);
}
}
static void Print2(BTNode root,int data) {
if(root!=null) {
if(data==root.data)
f2=true;
Print2(root.left,data);
Print2(root.right,data);
}
}
public static BTNode BuildTree(int[] treedata,int n){
if(treedata.length==0)
return null;
else{
if(n<treedata.length)
{
int l=n*2+1;
int r=n*2+2;
BTNode TreeRoot=new BTNode(treedata[n], BuildTree(treedata, l), BuildTree(treedata, r));
return TreeRoot;
}
else
return null;
}
}
static boolean f1=false;
static boolean f2=false;
public static void main(String args[]) throws Exception {
Scanner in=new Scanner(System.in);
String k=in.nextLine();
String tempdata=in.nextLine();
int l1=in.nextInt();
int r1=in.nextInt();
String[] data=tempdata.split(" ");
//System.out.println(l1+" "+r1);
BTNode treeroot;
int[] treedata=new int[data.length];
for(int i=0;i<treedata.length;i++)
{
treedata[i]=Integer.parseInt(data[i]);
//System.out.println(treedata[i]);
}
treeroot=BuildTree(treedata,0);
BTNode p = null,q=null;
p=treeroot;
q=treeroot;
Print(p,l1);
Print2(q,r1);
// System.out.println(f1);
// System.out.println(f2);
if(f1&&f2) {
BTNode res=lca(treeroot,l1,r1);
System.out.println(res.data);
}
else System.out.println(-1);
}
}//做的很挫,勉强能过
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享