235. 二叉搜索树的最近公共祖先

image.png

递归

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  12. //二叉搜索树的特点,有序, 先序递归
  13. if(root == null ) return null;
  14. //中 不处理
  15. if(root.val > p.val && root.val > q.val ) {
  16. TreeNode left = lowestCommonAncestor(root.left, p, q );
  17. return left;
  18. }
  19. if(root.val < p.val && root.val < q.val ) {
  20. TreeNode right = lowestCommonAncestor(root.right, p, q );
  21. return right;
  22. }
  23. return root;
  24. }
  25. }

迭代

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  12. while(root != null ) {
  13. if(root.val > p.val && root.val > q.val ) {
  14. root = root.left;
  15. } else if(root.val < p.val && root.val < q.val ) {
  16. root = root.right;
  17. } else {
  18. return root;
  19. }
  20. }
  21. return root;
  22. }
  23. }