-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_236.java
More file actions
14 lines (14 loc) · 796 Bytes
/
Copy pathproblem_236.java
File metadata and controls
14 lines (14 loc) · 796 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
236. Lowest Common Ancestor of a Binary Tree
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).” */
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p ,q);
TreeNode right = lowestCommonAncestor(root.right, p ,q);
if(left != null && right != null) return root;
return (left != null)? left : right;
}
}