68_getLowestCommonParentBST

package pers.lyt.java;

//题目
//	输入两个树结点,求它们的最低公共祖先。
//思路
//	该题首先要和面试官确定是否为二叉树,得到肯定答复后,还要确定是否为二叉搜索树,是否
//有父指针,或者仅仅是普通二叉树。
//	1.树为二叉搜索树时,最低公共祖先结点的大小在两个树结点大小的中间。
//	2.树为普通树时,使用遍历将子结点的信息往上传递。在左右子树中进行查找是否存在两个树
//结点,如果两个树结点分别在左右子树上,说明该根结点就是它们的最低公共祖先。
public class Offer68_getLowestCommonParentBST {
	public class TreeNode {
		int val = 0;
		TreeNode left = null;
		TreeNode right = null;

		public TreeNode(int val) {
			this.val = val;
		}
	}

	/*
	 * 二叉搜索树: 利用大小关系即可
	 */
	public TreeNode getLowestCommonParentBST(TreeNode root, TreeNode node1, TreeNode node2) {
		while (true) {
			if (root == null)
				return root;
			if (root.val < node1.val && root.val < node2.val)
				root = root.right;
			else if (root.val > node1.val && root.val > node2.val)
				root = root.right;
			else
				return root;
		}
	}

	/*
	 * 普通二叉树: 将下面结点的信息利用递归s往上传递
	 */
	public TreeNode getLowestCommonParent(TreeNode root, TreeNode node1, TreeNode node2) {
		if (root == null || root == node1 || root == node2)
			return root;
		TreeNode left = getLowestCommonParent(root.left, node1, node2);
		TreeNode right = getLowestCommonParent(root.right, node1, node2);
		return left == null ? right : right == null ? left : root;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值