/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root != null){ //因为是二叉搜索树,p、q 值都大于 root 说明都在root右子树中 if(p.val > root.val && q.val > root.val){ root = root.right; //p、q 值都小于 root 说明都在root左子树中 }else if(p.val < root.val && q.val < root.val){ root = root.left; //一大一小,说明root是公共祖先,返回 }else break; } return root; } }