一、题目内容

image.png

二、题解

解法1:

思路

image.png
image.png

代码

迭代法

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. while(root != null){
  4. if(root.val<p.val && root.val<q.val){ //都在右子树
  5. root = root.right;
  6. }
  7. else if(root.val>p.val && root.val>q.val){//都在左子树
  8. root = root.left;
  9. }
  10. else{
  11. break;
  12. }
  13. }
  14. return root;
  15. }
  16. }

递归法

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if(root.val<p.val && root.val<q.val){ //都在右子树
  4. return lowestCommonAncestor(root.right,p,q);
  5. }else if(root.val>p.val && root.val>q.val){//都在左子树
  6. return lowestCommonAncestor(root.left,p,q);
  7. }else{
  8. return root;
  9. }
  10. }
  11. }