面试题68 - I. 二叉搜索树的最近公共祖先
题目描述:
测试用例:
思路:
-
利用二叉搜索树的性质,左子树都比根小,右子树都比根大,中序遍历为递增序列
基本流程:
-
边界条件:
-
传入参数root为null,返回null
-
-
循环查看root是否为空并处理以下三种情况:(利用二叉搜索树的性质)
-
都比root小,则两个节点都在root左侧,root赋值为左子树
-
都比root大,则两个节点都在root右侧,root赋值为右子树
-
一个比root小,另一个比root大,则为跳出循环条件,即找到了最近的公共祖先
-
代码:
import java.util.Objects; public class P面试题68_IErChaSouSuoShuDeZuiJinGongGongZuXianLcof { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //二叉搜索树中序遍历为递增,左孩子小于根小于右孩子 //root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 public static void main(String[] args) { Solution solution = new P面试题68_IErChaSouSuoShuDeZuiJinGongGongZuXianLcof().new Solution(); // TO TEST TreeNode root = new TreeNode(6); TreeNode root1 = new TreeNode(2); TreeNode root2 = new TreeNode(8); TreeNode root3 = new TreeNode(0); TreeNode root4 = new TreeNode(4); TreeNode root5 = new TreeNode(7); TreeNode root6 = new TreeNode(9); TreeNode root7 = new TreeNode(3); TreeNode root8 = new TreeNode(5); root.left = root1; root.right = root2; root1.left = root3; root1.right = root4; root2.left = root5; root2.right = root6; root4.left = root7; root4.right = root8; root3.left = root3.right = root5.left = root5.right = root6.left = root6.right = root7.left = root7.right = root8.left = root8.right = null; System.out.println(solution.lowestCommonAncestor(root, root1, root4).val); } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /** * * 如果三种情况: * 1.都比根大:都在右侧 * 2.都比根小:都在左侧 * 3.一个比根大一个比根小 或者 存在等于根的:就是要找的祖先 * * 还有一个意外情况为开始的根为null */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (Objects.isNull(root)) return null; while (Objects.nonNull(root)){ if (root.val < p.val && root.val < q.val){ root = root.right; }else if (root.val > p.val && root.val > q.val){ root = root.left; }else{ break; } } return root; } } }