JAVA怎么求共同祖先_java – 二叉树中最低的共同祖先

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-21 09:12   30   0

将解决方案扩展到通用二叉树树的关键似乎在于找到连接根节点和目标节点的路径.获得此路径后,您可以轻松修改LCA功能以找到最低共同祖先.

下面的粗略实现使用java.util.concurrent.*中的LinkedBlockingQueue和java.util.*中的Stack – 但是,任何其他普通队列和堆栈也可以使用.该代码假定目标节点存在于树中.

public static void findPath2(Node target,Node top, Stack path){

LinkedBlockingQueue q1 = new LinkedBlockingQueue(), q2 = new LinkedBlockingQueue(),

q3 = new LinkedBlockingQueue();

Node n = top;

Node parrent = null;

while(n.getData().compareTo(target.getData())!= 0){

parrent = n;

if(n.right != null){

q2.add(n.right);

q3.add(parrent);

}

if(n.left != null){

q2.add(n.left);

q3.add(parrent);

}

n = q2.remove();

q1.add(n);

}

Stack s3 = new Stack(), s2 = new Stack();

while(!q3.isEmpty()){

s3.push(q3.remove());

}

for(int i = 1; i <= q2.size(); i++)

s3.pop();

while(!s3.isEmpty())

s2.push(s3.pop());

while(!q1.isEmpty())

s3.push(q1.remove());

LinkedBlockingQueue temp = new LinkedBlockingQueue();

while(!s2.isEmpty())

temp.add(s2.pop());

while(!temp.isEmpty())

s2.push(temp.remove());

path.push(s3.pop());

path.push(s2.pop());

while(!s3.isEmpty()){

n = s3.peek();

while(n.getData().compareTo(path.peek().getData()) != 0 && !s3.isEmpty()){

s3.pop();

s2.pop();

if(!s3.isEmpty())

n = s3.peek();

}

if(!s3.isEmpty()){

s3.pop();

path.push(s2.pop());

}

}

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP