题目
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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
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 nodes5
and1
is3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes5
and4
is5
, since a node can be a descendant of itself according to the LCA definition.
十分钟尝试
之前做过一道寻找LCA的问题,不过当时是个二叉搜索树,左子树都小于root,右子树都大于root,可以利用(root.val-p.val)*(root.val-q.val)>0 寻找,如果不成立,则没有公共祖先。
https://blog.csdn.net/hanruikai/article/details/85000183
上面的方法仅仅适用于二叉搜索树,因为有序性。这个二叉树,我们可以利用直觉的方法。如果寻找p和q的LCA,首先想到的是遍历二叉树找到p和q,在寻找的过程中,保存所有的父亲节点到有序集合(倒序)----stack,然后比较两个集合,第一个相同的元素就是LCA。
迭代的方案比较繁琐,看了看思路提示,可以用递归方法解决,类似于之前的方法,虽然不能根据乘积判断在那侧,但是可以递归寻找pq节点。判断两个节点在那侧。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//迭代方案较为复杂,学习一下递归方法
//出口条件
if(root==null||root==p||root==q){
//假如3个节点,返回是root.left 或者root.right
return root;
}
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(left!=null&&right!=null){
//pq分别在左右子树发现,返回root就是公共祖先
return root;
}
if(left==null&&right==null){
//不存在公共祖先
return null;
}
//左子树或者右子树集中存在pq,不是分布在两侧,也不是不存在pq节点
return left==null?right:left;
}
}