236. (LCA) Lowest Common Ancestor of a Binary Tree
Previous235. (LCA) Lowest Common Ancestor of a Binary Search TreeNext1644. Lowest Common Ancestor of a Binary Tree II
Last updated
Last updated
time: O(n)
space:O(n)
/*
236. Lowest Common Ancestor of a Binary Tree
1. ็ตๆญขๆขไปถ
2. ๆพๅทฆๅญๆจน
3. ๆพๅณๅญๆจน
4. ๅฆๆๅจๅทฆๅณๅญๆจนๆพๅฐpq, ไปฃ่กจpqไธๅๅจๅทฆไธๅๅจๅณ, rootๅฐฑๆๆฏLCS
5. ๅฆๆๅชๆๅจๆไธ้ๆพๅฐ, ไปฃ่กจpqๅจๅไธๅด, ๆไปฅLCSๅฐฑๆฏๆไธ้ๆพๅฐ็ๆฌ่บซ็ตๆ๏ผ้ก็ฎไธญๆๆๅฐLCSๅฏไปฅๆฏpๆqๆฌ่บซ๏ผ
time complexity: O(n), space complexity: O(n)
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p.equals(root) || q.equals(root) {
return root; // 1.terminal condition, find p,q or not find pq => null
}
TreeNode left = lowestCommonAncestor(root.left, p, q); //2.find left side for p, q
TreeNode right = lowestCommonAncestor(root.right, p, q); //3.find right side for p, q
if (left != null && right != null) {
return root; // 4.if find p,q in left and right side, root is LCS !
}
return left != null ? left : right; // 5.if only one side find p or q (it means p,q are all in one side), it's the answer because in question we allow a node to be a descendant of itself
}
}
ๅฆไธๅๆ่ทฏ, ็จ count, ๅ ถๅฏฆไธๆจฃๅฆ...
class Solution {
TreeNode res = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
dfs(root, p, q);
return res;
}
private int dfs(TreeNode node, TreeNode p, TreeNode q) {
if (node == null) {
return 0;
}
int left = dfs(node.left, p, q);
int right = dfs(node.right, p, q);
int self = (node.val == p.val || node.val == q.val) ? 1 : 0;
int count = left + right + self;
if (count == 2 && res == null) {
res = node;
}
return count;
}
}