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;
}
}
68_getLowestCommonParentBST
最新推荐文章于 2020-02-01 18:28:19 发布