Advertisement
Guest User

LCA on BST iteratively (while loop)

a guest
Jul 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.55 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.  
  14.     while (root != null) {
  15.         if (p.val < root.val && q.val < root.val) {
  16.             root = root.left;
  17.         } else if (p.val > root.val && q.val > root.val) {
  18.             root = root.right;
  19.         } else break;
  20.     }
  21.    
  22.     return root;
  23.   }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement