二叉树-公共祖先

import java.util.Scanner;

class Node{
	int id;
	Node left;
	Node right;
	Node(int id){
		this.id= id;
		left= null;
		right= null;
	}
}
class Find{
	Node FindNode(Node a, Node b, Node root){
		if(root== null||root== a|| root== b)
			return root;
			
		Node left= FindNode(a, b, root.left);		
		Node right= FindNode(a, b, root.right);
		
		if(left!= null&& right!= null) return root;
		if(left!= null) return left;
		return right;
	}
}
public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in= new Scanner(System.in);
		
		int n= in.nextInt();
		Find find= new Find();
		while(n!= -1){
			//build tree
			Node[] tree= new Node[n];
			for(int i= 0; i<n; i++)
				tree[i]= new Node(i);
			
			for(int i= 0; i< n; i++){
				int leftId= in.nextInt();
				if(leftId!= -1) tree[i].left= tree[leftId];
				int rightId= in.nextInt();
				if(rightId!= -1) tree[i].right= tree[rightId];
			}
			
			int m= in.nextInt();

			while(m--!= 0){
				System.out.println(find.FindNode(tree[in.nextInt()], tree[in.nextInt()], tree[0]).id);
				
			}
			n= in.nextInt();
		}
	}

}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kxyspace/article/details/53995843
个人分类: 数据结构
上一篇关于JAVA小程序完整打包过程
下一篇Single Number
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭