Last active
August 8, 2017 02:34
-
-
Save cixuuz/640bb9b86b242829f9b62744b35e2341 to your computer and use it in GitHub Desktop.
[236. Lowest Common Ancestor of a Binary Tree] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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