Java 两结点的最近公共祖先结点

public class Main {

	public static void main(String[] args) throws Exception {
		BinaryTreeNode root = new BinaryTreeNode();
		BinaryTreeNode n1 = new BinaryTreeNode();
		BinaryTreeNode n2 = new BinaryTreeNode();
		BinaryTreeNode n3 = new BinaryTreeNode();
		BinaryTreeNode n4 = new BinaryTreeNode();
		BinaryTreeNode n5 = new BinaryTreeNode();
		root.value = 50;
		n1.value = 25;
		n2.value = 75;
		n3.value = 10;
		n4.value = 35;
		n5.value = 35;
		root.leftNode = n1;
		root.rightNode = n2;
		n1.leftNode = n3;
		n1.rightNode = n4;
		System.out.println(findNode(root,n1,n5).value);
	}
	
	//找到两个结点的最近公共祖先
	public static BinaryTreeNode findNode(BinaryTreeNode root, BinaryTreeNode node1, BinaryTreeNode node2){
		List path1 = new ArrayList();
		List path2 = new ArrayList();
		boolean flag1 = false;
		boolean flag2 = false;
		flag1 = getPath(root,node1,path1);
		flag2 = getPath(root,node2,path2);
		if(flag1 == false || flag2 == false){
			return null;
		}
		return findCommonNode(path1,path2);
	}

	//找到目标结点的路径
	public static boolean getPath(BinaryTreeNode root, BinaryTreeNode node, List path){
		if(root!=null){
			path.add(root);
		}
		if(node == root){
			return true;
		}
		if(root == null){
			return false;
		}
		boolean found = getPath(root.leftNode,node,path);
		if(!found){
			found = getPath(root.rightNode, node,path);
		}
		if(!found){
			path.remove(path.size()-1);
		}
		return found;
	}

	//找到两条路径的最后一个相同的结点
	public static BinaryTreeNode findCommonNode(List path1, List path2){
		BinaryTreeNode result = path1.get(0);
		int temp = 0;
		while(temp

你可能感兴趣的:(Java 两结点的最近公共祖先结点)