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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
一刷
题解:这里跟236不一样的是,它不再限定在binary search tree, 而是任意一个binary tree. 然后DFS左右子树去寻找node p和q
/**
* 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){
return right;
}
else{
if(right == null) return left;
else return root;
}
}
}
二刷
同上,其实会有很多的重复运算,可以考虑用map<Node, [true, false]>来表示在这个node的左还是右子树找到[p,q]
/**
* 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){//not found
return right;
}
if(right == null) return left;
return root;
}
}
三刷
用in-order来给每个点标上记号, 在左子树的index都小于root, 右子树的index都大于root
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int index = 0;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//in-order traverse
Map<TreeNode, Integer> map = new HashMap<>();
inorder(root, map);
TreeNode node = root;
int b = map.get(p), c = map.get(q);
while(node!=null){
int a = map.get(node);
if(a == b || a == c) return node;
else if(b<a && c<a) node = node.left;
else if(b>a && c>a) node = node.right;
else return node;
}
return node;
}
private void inorder(TreeNode root, Map<TreeNode, Integer> map){
if(root == null) return;
inorder(root.left, map);
map.put(root, index++);
inorder(root.right, map);
}
}