题目来源:
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
题目描述:
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉树中。
解题思路:
递归搜索左右子树,如果左子树和右子树都不为空,说明最近父节点一定在根节点。
反之,如果左子树为空,说明两个节点一定在右子树;
同理如果右子树为空,说明两个节点一定在左子树。
代码如下:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
} else {
return left == null ? right : left;
}
}
}