File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">week13-2. lowest-common-ancestor-of-a-binary-search-tree</a>
3+ * <li>Description: find the lowest common ancestor (LCA) node of two given nodes in the BST. </li>
4+ * <li>Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree </li>
5+ * <li>Time Complexity: O(H), Runtime 5ms </li>
6+ * <li>Space Complexity: O(1), Memory 44.91MB </li>
7+ */
8+
9+ class Solution {
10+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
11+ TreeNode node = root ;
12+ while (node != null ) {
13+ if (p .val < node .val && q .val < node .val ) {
14+ node = node .left ;
15+ } else if (p .val > node .val && q .val > node .val ) {
16+ node = node .right ;
17+ } else {
18+ return node ;
19+ }
20+ }
21+
22+ throw new IllegalArgumentException ();
23+ }
24+ }
You can’t perform that action at this time.
0 commit comments