递归
/** * 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) { //二叉搜索树的特点,有序, 先序递归 if(root == null ) return null; //中 不处理 if(root.val > p.val && root.val > q.val ) { TreeNode left = lowestCommonAncestor(root.left, p, q ); return left; } if(root.val < p.val && root.val < q.val ) { TreeNode right = lowestCommonAncestor(root.right, p, q ); return right; } return root; }}
迭代
/** * 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 ) { if(root.val > p.val && root.val > q.val ) { root = root.left; } else if(root.val < p.val && root.val < q.val ) { root = root.right; } else { return root; } } return root; }}