公共父节点

/**
 * node A and node B, to get the closest common parent node. 
 *
 */
public class CommonParent {
	public Stack stack = new Stack();

	
	public Node getCommonParent(Node root, Node a, Node b) throws Exception{
		assert(root != null);
		assert(a != null);
		assert(b != null);
		
		Node node = find(root, a, b);
		if(node == null){
			throw new Exception("cannot find a or b.");
		}
		Node target = null;
		if(node.value == a.value){
			target = b;
		}
		if(node.value == b.value){
			target = a;
		}
		boolean result = dfs(node, target);
		if(result){
			//throw new Exception("can not find target : " + target.value);
			System.out.println("Found it, the common parent is : " + node.value);
			return node;
		}
		while(!stack.isEmpty()){
			Node parent = (Node) stack.pop();
			if(parent.right != null){
				result = dfs(parent.right, target);
				if(result){
					System.out.println("Found it, the common parent is : " + parent.value);
					return parent;
				}
			}

		}
		if(!result){
			throw new Exception("can not find the other node");
		}
		return null;
	}
	
	
	private Node find(Node parent, Node a, Node b) throws Exception {
		assert(true);
		Node node = null;
		stack.push(parent);
		if((parent.value==a.value) || (parent.value==b.value)){
			stack.pop();
			return parent;
		}
		if(parent.left != null){
			node = find(parent.left, a, b);
			if(node != null){
				return node;
			}
		}
		if(parent.right != null){
			node = find(parent.right, a, b);
			if(node != null){
				return node;
			}
		}
		stack.pop();
		return null;
	}
	
	private boolean dfs(Node node, Node target){
		assert(true);
		boolean b = false;
		if(node.value == target.value){
			return true;
		}
		if(node.left != null){
			b = b || dfs(node.left, target);
		}
		if(node.right != null){
			b = b || dfs(node.right, target);
		}
		
		return b;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		int[] array = {5,3,7,1,9,6,2,8,4};
		bt.buildTree(array);
		bt.printTree();

		CommonParent cp = new CommonParent();
		Node a = new Node(3);
		Node b = new Node(6);
		try {
			cp.getCommonParent(bt.root, a, b);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值