Visualize LCA in a BST step by step. Watch the algorithm walk toward the split point where p and q diverge, with no recursion or parent pointers needed.
About this algorithm
The lowest common ancestor (LCA) of two nodes is the deepest node that has both of them in its subtree, where a node counts as its own descendant. In a binary search tree you can find it with one walk from the root and no extra memory: go down while both values lie on the same side, and stop at the first node where they part ways. This is LeetCode 235.
Use this version whenever the tree is a binary search tree. For any other binary tree there is no ordering to steer by, so you need the general method that searches both subtrees at every node and costs O(N); the tree family's LCA page shows that one. In a search tree the LCA also answers range questions: every value between the two keys lies in the LCA's subtree, and the path between two nodes runs through it, so a distance between them is the depth of each minus twice the depth of the LCA.
An ancestor only means something for nodes that exist. This page looks both keys up first and stops with "undefined" if either is missing; otherwise the walk below would happily name a node for keys that are not there.
Start at the root. If both values are smaller than the current node, both live in its left subtree, and so does their lowest common ancestor.
If both are larger, move to the right child for the same reason.
If one value is smaller and the other larger, or one of them equals the current node, the two cannot both be below either child. The current node is the answer.
The page loads 20 at the root, 10 and 30 below it, 5 and 15 under 10 and 25 and 35 under 30, and asks for the LCA of 5 and 15. Both are in the tree. At 20, both 5 and 15 are smaller, so go left. At 10, 5 is smaller and 15 is larger, so they split here: the answer is 10, found in 2 comparisons. Try 5 and 35 and the split happens at the root, so the answer is 20. Try 25 and 30: at 20 both are larger, go right; at 30 one key equals the node, so the answer is 30 itself, because a node counts as its own ancestor.
Above the split, both keys sat in one subtree, so every node passed was an ancestor of both. Below the split they are in different subtrees, so no deeper node holds both. That makes the split node the deepest shared ancestor, with no need to look anywhere else.
Time: the walk follows one root-to-node path, so it costs the height of the tree; the presence check before it is two more searches of the same cost. Space: only the current node is kept, so the loop needs constant memory; a recursive version would use O(H) stack.