MrainW's Home

All things come to those who wait!

0%

LeetCode 1644. Lowest Common Ancestor of a Binary Tree II

Question

Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.

According to the definition of LCA on Wikipedia: β€œThe lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)”. A descendant of a node x is a node y that is on the path from node x to some leaf node.

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/

Solution

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode pNode = dfs(root, p.val), qNode = dfs(root, q.val);
return (qNode == null || pNode == null) ? null : lca(root, pNode, qNode);
}
private TreeNode dfs(TreeNode cur, int target){
if (cur == null) return null;
if (cur.val == target) return cur;
TreeNode left = dfs(cur.left, target);
TreeNode right = dfs(cur.right, target);
return left == null ? right : left;
}
public TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lca(root.left, p, q);
TreeNode right = lca(root.right, p, q);
if (left != null && right != null) return root;
if (left != null) return left;
if (right != null) return right;
return null;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels