Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode 236. Lowest Common Ancestor of a Binary Tree

Woodyiiiiiii opened this issue · comments

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]

image

Example 1:

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.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

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

实际上就是树形DP的问题。后序遍历,从左子树和右子树收集信息,到当前根节点处理。

处理信息分为几种情况:

  1. 左子树和右子树不为空,则该根节点就是最近公共祖先;
  2. 当前根节点为题目所给节点,左子树或右子树信息也返回的是所给节点,那么该根节点就是祖先;3. 左子树或右子树信息返回的是所给节点,而根节点不是,则返回所给节点;
  3. 当前根节点为题目所给节点,左子树或右子树信息返回空, 则返回所给节点;
  4. 其余情况为空;
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return findLRC(root, p, q);
    }
    public TreeNode findLRC(TreeNode node, TreeNode p, TreeNode q) {
        if (node == null) {
            return null;
        }
        TreeNode left = findLRC(node.left, p, q);
        TreeNode right = findLRC(node.right, p, q);
        if ((left == p && right == q) ||
            (left == q && right == p))
            return node;
        else if ((node == p || node == q) 
                  && (right != null || left != null))
            return node;
        else if (left != null || right != null)
            return left == null ? right : left;
        else if (node == p || node == q)
            return node;
        else
            return null;
    }
}

参考资料:
LeetCode原题