File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * class TreeNode {
4+ * val: number
5+ * left: TreeNode | null
6+ * right: TreeNode | null
7+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.left = (left===undefined ? null : left)
10+ * this.right = (right===undefined ? null : right)
11+ * }
12+ * }
13+ *
14+ * Time Complexity: O(h) where h is the height of the tree
15+ * Space Complexity: O(1)
16+ */
17+ function lowestCommonAncestor ( root : TreeNode | null , p : TreeNode | null , q : TreeNode | null ) : TreeNode | null {
18+ if ( p . val < root . val && q . val < root . val ) {
19+ return lowestCommonAncestor ( root . left , p , q ) ;
20+ } else if ( p . val > root . val && q . val > root . val ) {
21+ return lowestCommonAncestor ( root . right , p , q ) ;
22+ }
23+
24+ return root ;
25+ }
You can’t perform that action at this time.
0 commit comments