一、题目
分析
求两个节点的最近公共祖先节点:(根据LCA定义,一个节点可以是他自己的后代)
1、一定在根结点到这两个节点的路径中。
2、一定是离根结点最远的公共节点
那么代码设计
1、要从根结点找到两个节点的路径并记录保存
2、找公共节点,并且是最近的公共节点
二、java代码
1.最简单直白的方法,调用两次找路径函数,分别保存,然后再遍历,找到离根结点最远的公共节点就是最近公共父结点
/**
* 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 || p==null || q==null) return null;
List<TreeNode> pathp = new ArrayList<>();
List<TreeNode> pathq = new ArrayList<>();
pathp.add(root);
pathq.add(root);
getPath(root, p, pathp);
getPath(root, q, pathq);
TreeNode lca = null;
for(int i=0; i<pathp.size() && i<pathq.size(); i++) {
if(pathp.get(i) == pathq.get(i)) lca = pathp.get(i);
else break;
}
return lca;
}
private boolean getPath(TreeNode root, TreeNode n, List<TreeNode> path) {
if(root==n) {
return true;
}
if(root.left!=null) {
path.add(root.left);
if(getPath(root.left, n, path)) return true;
path.remove(path.size()-1);
}
if(root.right!=null) {
path.add(root.right);
if(getPath(root.right, n, path)) return true;
path.remove(path.size()-1);
}
return false;
}
}
2.纯递归方法
/**
* 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) {
return root;
}
TreeNode l = lowestCommonAncestor(root.left, p, q);
TreeNode r = lowestCommonAncestor(root.right, p, q);
return l != null && r != null ? root : l == null ? r : l;
}
}
分析:
两个节点的公共父节点要么在左子树有么在右子树。所以采用递归的方式来遍历左子树和右子树。直到当前节点为空或者当前节点的为p或者q节点。
这个basecase问题是,递归到最后root==null或者rooot==p/q,返回root(此时的root不一定是根结点啦,因为后面递归的是root.left还有root.right),要么是空,要么是p要么是q(因为p q也可以作为自身的父结点)
然后下面是两个递归,一个是左孩子和p q的递归,一个是右孩子和p q的递归,总能找到最后要么root==null/p/q的情况
然后最后的返回值是 return l != null && r != null ? root : l == null ? r : l;
(1)左子树和右子树都为不为空(公共节点不在左右子树上),那么root就是p q的公共父结点
(2)左子树为空,那么在右子树上,否则在左子树上