Given the root
of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p
and q
. If either node p
or q
does not exist in the tree, return null
. All values of the nodes in the tree are unique.
According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p
and q
in a binary 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)". A descendant of a node x
is a node y
that is on the path from node x
to some leaf node.
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.
思路:这题跟 Lowest Common Ancestor of a Binary Tree_leetcode 解题思路-CSDN博客 的区别是,这题如果其中一个node不在tree里面,就要返回null,所以要去搜索整个tree,然后用全局变量去记录是否visit过p和q,然后才能返回LCA,否则就是返回null;其余代码跟上面LCA一模一样
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean pfind = false;
private boolean qfind = false;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode LCA = findLCA(root, p, q);
return pfind && qfind ? LCA : null;
}
private TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) {
return root;
}
TreeNode leftnode = findLCA(root.left, p, q);
TreeNode rightnode = findLCA(root.right, p, q);
// 一定要上面的dfs运行完,搜索完整个tree了,才做判断,因为要去在整个tree里面搜p,q
// 下面的部分不能提前,否则没办法搜整个tree;
if(root == p) {
pfind = true;
return root;
}
if(root == q) {
qfind = true;
return root;
}
if(leftnode == null) {
return rightnode;
} else if(rightnode == null) {
return leftnode;
} else {
return root;
}
}
}