|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=236 lang=javascript |
| 3 | + * |
| 4 | + * [236] Lowest Common Ancestor of a Binary Tree |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * function TreeNode(val) { |
| 11 | + * this.val = val; |
| 12 | + * this.left = this.right = null; |
| 13 | + * } |
| 14 | + */ |
| 15 | +/** |
| 16 | + * @param {TreeNode} root |
| 17 | + * @param {TreeNode} p |
| 18 | + * @param {TreeNode} q |
| 19 | + * @return {TreeNode} |
| 20 | + */ |
| 21 | +var lowestCommonAncestor = function(root, p, q) { |
| 22 | + if (!root || p === root || q === root) return root |
| 23 | + const left = lowestCommonAncestor(root.left, p, q) |
| 24 | + const right = lowestCommonAncestor(root.right, p, q) |
| 25 | + if (left && right) return root |
| 26 | + return left ? left : right |
| 27 | +}; |
| 28 | +// @lc code=end |
| 29 | + |
0 commit comments