236 Lowest Common Ancestor of a Binary Tree

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:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Note:

  • All of the nodes' values will be unique.
  • p and q are different and both values will exist in the binary tree.

解释下题目:

找到两个给定节点的最下面的那个公共祖先。

1. 递归

实际耗时:5ms

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;
    }
    if (left == null) {
        return right;
    } else {
        return left;
    }
}

  考虑到树的题目,大概率肯定用递归,简单方便理解。首先对于一个节点,如果它已经是空(说明已经到叶子节点了)或者成功和p和q匹配上了,那就返回它。然后树的左边的节点和右边的节点也如此做即可。最后如果左右两边都不是空,说明找到了答案,如果有一个不是空则返回那个,当然其实如果两个都是空说明没有,但是这道题确保一定有,所以可以这么写。

时间复杂度O(n)
空间复杂度O(递归)

推荐阅读更多精彩内容