Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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).”
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
[2, 10^5].-10^9 <= Node.val <= 10^9Node.val are unique.p != qp and q will exist in the tree.When the function lowestCommonAncestor is called with the given example inputs, the expected output is the value of the lowest common ancestor of the two nodes.
let root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
let p = root.left; // 5
let q = root.right; // 1
console.log(lowestCommonAncestor(root, p, q).val); // Output: 3
p = root.left; // 5
q = root.left.right.right; // 4
console.log(lowestCommonAncestor(root, p, q).val); // Output: 5
Memory: 0
CPU: 0