【剑指offer】 面试题50: 树中两个结点的最低公共祖先(二叉排序数)

题目描述:

给定一棵树,同时给出树中的两个结点,求它们的最低公共祖先。


10 8 6 0 0 9 0 0 20 15 0 0 0
6 15


存在, 10



基本思想为:从树根开始

1、该节点的值为t,如果t大于t1和t2,说明t1和t2都位于t的左侧,所以它们的共同祖先必定在t的左子树中,从t.left开始搜索;

2、如果t小于t1和t2,说明t1和t2都位于t的右侧,那么从t.right开始搜索;

3、如果t1<t< t2,说明t1和t2位于t的两侧,那么该节点t为公共祖先。


如果t1是t2的祖先,那么应该返回t1的父节点;同理,如果t2是t1的祖先,应该返回t2的父节点。




	/**
	 * 二叉树中任意两个节点的最近公共祖先
	 * 
	 * 如果二叉树为二叉查找树
	 * 
	 */
	public static boolean LowestCommonAncestor(BinaryTreeNode root, int a, int b) {

		BinaryTreeNode parent = null;
		BinaryTreeNode curRoot = root;
		// a, b 有序
		if(a > b) {
			int tmp = a;
			a = b;
			b = tmp;
		}
		
		while(curRoot != null) {
			// 如果当前结点大于a,b , 则在左子树
			if(curRoot.elem > b) {
				parent = root;
				curRoot = curRoot.left;
				// 如果当前结点小于a,b , 则在右子树
			} else if(curRoot.elem < a) {
				parent = root;
				curRoot = curRoot.right;
				// 如果当前结点等于a,b , 则在返回当前结点的父节点
			} else if(curRoot.elem == a || curRoot.elem == b) {
				result = parent.elem;
				return true;
				// 如果当前结点正好介于a, b 之间
			} else {
				result = curRoot.elem;
				return true;
			}
		}
		return false;
	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值