题目
设计并实现一个算法,找出二叉树中某两个节点的第一个共同祖先。不得将其他的节点存储在另外的数据结构中。注意:这不一定是二叉搜索树。
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
解题思路
- 如果p、q都在左子树中,继续在左子树中查找
- 如果p、q都在右子树中,继续在右子树中查找
- 否则找到了首个公共祖先,包含3种情况
- p、q分别在左右子树中
- p是q的父节点
- q是p的父节点
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode ans;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
ans = root;
search(root, p, q);
return ans;
}
private void search(TreeNode node, TreeNode p, TreeNode q) {
if (node == null) return;
// 如果p、q都在左子树中,继续在左子树中查找
if (search(node.left, p) && search(node.left, q)) search(node.left, p, q);
// 如果p、q都在右子树中,继续在右子树中查找
else if (search(node.right, p) && search(node.right, q)) search(node.right, p, q);
// 找到了首个公共祖先
else ans = node;
}
private boolean search(TreeNode node, TreeNode target) {
if (node == null) return false;
if (node == target) return true;
return search(node.left, target) || search(node.right, target);
}
}