java-75-二叉树两结点的最低共同父结点

本文介绍了一种寻找二叉树中两个指定节点的最低公共祖先的方法。通过递归构建从根节点到目标节点的路径,并找到这两条路径上的最后一个相同节点,即为所求最低公共祖先。

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


import java.util.LinkedList;
import java.util.List;

import ljn.help.*;
public class BTreeLowestParentOfTwoNodes {

public static void main(String[] args) {
/*
* node data is stored in leverOrder.'0' represents null node.
* e.g.
* int[] data={1,8,7,9,2,0,0,0,0,4,7};
* the tree is:
* 1
/ \
8 7
/ \
9 2
/ \
4 7
*/
int[] data={1,8,7,9,2,0,0,0,0,4,7};
Node head=Helper.createTree(data);
Node node1=new Node(4);
Node node2=new Node(9);//their lowest parent should be 8
LinkedList<Node> path1=new LinkedList<Node>();//should be 1,8,2,4
LinkedList<Node> path2=new LinkedList<Node>();//should be 1,8,9
createPath(head,node1,path1);
createPath(head,node2,path2);
Node lowestParent=lastCommonNode(path1,path2);
System.out.println(lowestParent.getData());
}

//create a path from BTree's root to the specific node
public static boolean createPath(Node head,Node node,LinkedList<Node> path){
if(head.getData()==node.getData()){
return true;
}
boolean found=false;
path.addLast(head);
if(head.getLeft()!=null){
found=createPath(head.getLeft(),node,path);
}
if(!found&&head.getRight()!=null){
found=createPath(head.getRight(),node,path);
}
if(!found){
path.removeLast();
}
return found;
}
/*
* find 'lastCommonNode' of two list and return.
* e.g
* list1=1,2,3,5
* list2=1,2,3,4
* we return 3
*/
public static Node lastCommonNode(List<Node> list1,List<Node> list2){
Node result=null;
int len1=list1.size();
int len2=list2.size();
if(len1==0||len2==0){
return null;
}
for(int i=0,j=0;i<len1&&j<len2;i++,j++){
if(list1.get(i)==list2.get(j)){
result=list1.get(i);
}
}
return result;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值