|
| 1 | +// Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. |
| 2 | +// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” |
| 3 | +// Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] |
| 4 | +// |
| 5 | +// Example 1: |
| 6 | +// |
| 7 | +// Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 |
| 8 | +// Output: 6 |
| 9 | +// Explanation: The LCA of nodes 2 and 8 is 6. |
| 10 | +// |
| 11 | +// Example 2: |
| 12 | +// |
| 13 | +// Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 |
| 14 | +// Output: 2 |
| 15 | +// Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. |
| 16 | +// |
| 17 | +// Note: |
| 18 | +// |
| 19 | +// All of the nodes' values will be unique. |
| 20 | +// p and q are different and both values will exist in the BST. |
| 21 | +/** |
| 22 | + * Definition for a binary tree node. |
| 23 | + * function TreeNode(val) { |
| 24 | + * this.val = val; |
| 25 | + * this.left = this.right = null; |
| 26 | + * } |
| 27 | + */ |
| 28 | +/** |
| 29 | + * @param {TreeNode} root |
| 30 | + * @param {TreeNode} p |
| 31 | + * @param {TreeNode} q |
| 32 | + * @return {TreeNode} |
| 33 | + */ |
| 34 | + |
| 35 | +/** 1) Recursion */ |
| 36 | +function lowestCommonAncestor(root, p, q) { |
| 37 | + if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q); |
| 38 | + else if (p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right, p, q); |
| 39 | + else return root; |
| 40 | +} |
| 41 | + |
| 42 | +/** 2) Iteration */ |
| 43 | +function lowestCommonAncestor(root, p, q) { |
| 44 | + while (root != null) { |
| 45 | + if (p.val > root.val && q.val > root.val) root = root.right; |
| 46 | + else if (p.val < root.val && q.val < root.val) root = root.left; |
| 47 | + else return root; |
| 48 | + } |
| 49 | +} |
0 commit comments