LeetCode – Lowest Common Ancestor of a Binary Search Tree (Java)
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
Analysis
This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle.
Java Solution 1 - Recursive
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode m = root; if(m.val > p.val && m.val < q.val){ return m; }else if(m.val>p.val && m.val > q.val){ return lowestCommonAncestor(root.left, p, q); }else if(m.val<p.val && m.val < q.val){ return lowestCommonAncestor(root.right, p, q); } return root; } |
Java Solution 2 - Iterative
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode t = root; while(t!=null){ if(p.val >t.val && q.val >t.val){ t = t.right; }else if (p.val<t.val && q.val<t.val){ t = t.left; }else{ return t; } } return null; } |
<pre><code> String foo = "bar"; </code></pre>
-
XD_Coder
-
Tim
-
Matias SM
-
Long Jiao
-
NB****