题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
解题思路:1.调整p,q使得p<=q
2.递归问题定义,root为树中找pq的父节点;如果root.val小于p证明root.val的值太小,遍历右子树。如果root.val的值大于q证明值太大遍历左子树
3.递归边界,如果当前root.val大于等于且root.val小于等于q,就是答案
import java.util.*;
public class Solution {
public int lowestCommonAncestor (TreeNode root, int p, int q) {
if(p>q){
int t = p;
p = q;
q = t;
}
if(p <= root.val && root.val <= q)return root.val;
if(q<root.val)return lowestCommonAncestor(root.left,p,q);
return lowestCommonAncestor(root.right,p,q);
}
}