题目链接
首个共同祖先
题目描述
注意点
- 所有节点的值都是唯一的
- p、q 为不同节点且均存在于给定的二叉树中
解答思路
- 第一种思路是后序遍历找到包含p和q时的根节点(注意可能是p或q作为根节点),对于任一节点node,会先查找其左子树leftTree,再查找右子树rightTree,如果其左右子树再加上该节点形成的子树中包含了p和q,说明node是p和q的共同祖先,又因为要找到首个共同祖先,所以需要使用一个全局变量res,当找到了第一个共同祖先,就写入res,且不再更新
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode res;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
postOrder(root, p, q);
return res;
}
public int postOrder(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || res != null) {
return 0;
}
int sum = 0;
sum += postOrder(root.left, p, q);
sum += postOrder(root.right, p, q);
if (root == p || root == q) {
sum += 1;
}
if (sum == 2) {
res = root;
return 0;
}
return sum;
}
}
关键点
- 后序遍历的思想
- 将访问的子树中包含的p或q的数量返回给子树的根节点
- 当找到了首个共同祖先res,res的根节点肯定也是p和q的共同祖先,为了方便后续不再更新res,返回给根节点p或q的数量sum为0