Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // **Constraints:
- // * The number of nodes in the tree is in the range [2, 105].
- // * -109 <= Node.val <= 109
- // * All Node.val are unique.
- // * p != q
- // * p and q will exist in the tree.
- /**
- * Definition for a binary tree node.
- * class TreeNode {
- * val: number
- * left: TreeNode | null
- * right: TreeNode | null
- * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.left = (left===undefined ? null : left)
- * this.right = (right===undefined ? null : right)
- * }
- * }
- */
- function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
- if (root === null)
- return null;
- if (root.val === p.val || root.val === q.val)
- return root;
- const lcaInLeft = lowestCommonAncestor(root.left, p, q);
- const lcaInRight = lowestCommonAncestor(root.right, p, q);
- if (lcaInLeft && lcaInRight)
- return root;
- return lcaInLeft ? lcaInLeft : lcaInRight;
- }
Advertisement
Add Comment
Please, Sign In to add comment