给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
本题的解题思路:
已知搜索树的比父节点大的节点在右边,比父节点小的左边。
所以,当p,q两个节点的val都小于root节点的val的时候,就可以向左边遍历,反之右边也是一样。当p,q节点一个在左边,一个在右边的时候就找到了父节点。
这个题目类似二分查找。
非递归做法:
- class Solution {
- public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
- TreeNode ancestor = root;
- while (true) {
- if (p.val < ancestor.val && q.val < ancestor.val) {
- ancestor = ancestor.left;
- } else if (p.val > ancestor.val && q.val > ancestor.val) {
- ancestor = ancestor.right;
- } else {
- break;
- }
- }
- return ancestor;
- }
- }
递归做法:
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- TreeNode search(TreeNode root, TreeNode p, TreeNode q){
- if(root == null )
- return null;
- if(root.val >= p.val && root.val <= q.val)
- return root;
- else if(root.val >= p.val && root.val >= q.val){ //节点都在左子树
- return lowestCommonAncestor(root.left,p,q);
- }
- else
- return lowestCommonAncestor(root.right,p,q);
- }
- public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
- if(p.val > q.val)
- return search(root,q,p);
- else return search(root,p,q);
-
- }
- }