Guest User

Untitled

a guest
Jul 19th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. //Recursive solution
  2. //Time: O(n), 13ms
  3. //Space: O(h)
  4. class Solution {
  5. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  6. if(root == null) return null;//Base case 1: Not found
  7. if(root == p) return p;//Base Case 2: Found one
  8. if(root == q) return q;
  9. TreeNode left = lowestCommonAncestor(root.left, p, q);
  10. TreeNode right = lowestCommonAncestor(root.right, p, q);
  11. if(left != null && right != null) {//Case 1, p and q are in different branch of root
  12. return root;
  13. }
  14. if(left == null) {//Case 2, p and q are both in right subtree OR Case 4, p and q are not decedents of the root
  15. return right;
  16. } else {//Case 3, p and q are both in left subtree
  17. return left;
  18. }
  19. }
  20. }
  21. /**
  22. * Definition for a binary tree node.
  23. * public class TreeNode {
  24. * int val;
  25. * TreeNode left;
  26. * TreeNode right;
  27. * TreeNode(int x) { val = x; }
  28. * }
  29. */
Add Comment
Please, Sign In to add comment