Advertisement
Guest User

LCA on BST recursive

a guest
Jul 20th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  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. public class Solution {
  11.    
  12.     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  13.       if (root == null)
  14.         return null;
  15.      
  16.       // both p and q are less than root
  17.       // their ancestor must be in root.left
  18.       if (p.val < root.val && q.val < root.val)
  19.         return lowestCommonAncestor(root.left, p, q);
  20.          
  21.       // both p and q are greater than root
  22.       // their ancestor must be in root.right
  23.       if (p.val > root.val && q.val > root.val)
  24.         return lowestCommonAncestor(root.right, p, q);
  25.          
  26.       return root;
  27.     }
  28.  
  29.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement