Given a BST, find the lowest common ancestor (LCA) of two given nodes p and q. LCA is defined as the lowest node that has both p and q as descendants.

Input: root=[6,2,8,0,4,7,9], p=2, q=8 → Output: 6Input: root=[6,2,8,0,4,7,9], p=2, q=4 → Output: 2

Exploit BST property: if both p and q are less than root, LCA is in left subtree. If both greater, in right subtree. Otherwise, root is the LCA.

class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while (root != null) { if (p.val < root.val && q.val < root.val) root = root.left; else if (p.val > root.val && q.val > root.val) root = root.right; else return root; } return null; } }