Given two nodes of a binary tree p
and q
, return their lowest common ancestor (LCA).
Each node will have a reference to its parent node. The definition for Node
is below:
class Node { public int val; public Node left; public Node right; public Node parent; }
According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
Constraints:
- The number of nodes in the tree is in the range
[2, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
exist in the tree.
思路:注意node val全部是unique的,所以可以用set来收集一条路,另外一条路往上走,如果遇见node在set里面,立刻返回。T: log(h) S: log(h)
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
};
*/
class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
HashSet<Integer> ppath = new HashSet<>();
Node cur = p;
while(cur != null) {
ppath.add(cur.val);
cur = cur.parent;
}
cur = q;
while(cur != null) {
if(ppath.contains(cur.val)) {
return cur;
}
cur = cur.parent;
}
return null;
}
}
如果题目限制memory,那么这题就是两个linked list求交点那题;
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
};
*/
class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
int plen = getLength(p);
int qlen = getLength(q);
if(plen > qlen) {
return findLCA(p, q, plen - qlen);
} else {
// plen < qlen;
return findLCA(q, p, qlen - plen);
}
}
// make assumption plen > qlen;
private Node findLCA(Node p, Node q, int step) {
while(step > 0) {
p = p.parent;
step--;
}
while(p != q) {
p = p.parent;
q = q.parent;
}
return p;
}
private int getLength(Node node) {
int len = 0;
while(node != null) {
node = node.parent;
len++;
}
return len;
}
}