Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 8, 2017 02:34
Show Gist options
  • Save cixuuz/640bb9b86b242829f9b62744b35e2341 to your computer and use it in GitHub Desktop.
Save cixuuz/640bb9b86b242829f9b62744b35e2341 to your computer and use it in GitHub Desktop.
[236. Lowest Common Ancestor of a Binary Tree] #leetcode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || 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;
if (left != null) return left;
if (right != null) return right;
return null;
}
}
public class Solution1 {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
Map<TreeNode, TreeNode> parents = new HashMap<>();
parents.put(root, null);
while (!parents.containsKey(p) || !parents.containsKey(q)) {
TreeNode node = stack.pop();
if (node.left != null) {
stack.push(node.left);
parents.put(node.left, node);
}
if (node.right != null) {
stack.push(node.right);
parents.put(node.right, node);
}
}
Set<TreeNode> ancestors = new HashSet<>();
while (p != null) {
ancestors.add(p);
p = parents.get(p);
}
while (!ancestors.contains(q)) {
q = parents.get(q);
}
return q;
}
}
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
stack = [root]
parents = {root: None}
while p not in parents or q not in parents:
node = stack.pop()
if node.left:
stack.append(node.left)
parents[node.left] = node
if node.right:
stack.append(node.right)
parents[node.right] = node
ancestors = set()
while p:
ancestors.add(p)
p = parents[p]
while q not in ancestors:
q = parents[q]
return q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment