一、题目内容
二、题解
解法1:
思路

代码
迭代法
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root != null){ 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; }}
递归法
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val<p.val && root.val<q.val){ //都在右子树 return lowestCommonAncestor(root.right,p,q); }else if(root.val>p.val && root.val>q.val){//都在左子树 return lowestCommonAncestor(root.left,p,q); }else{ return root; } }}