Skip to content

LeetCode 236. Lowest Common Ancestor of a Binary Tree #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Woodyiiiiiii opened this issue Apr 24, 2020 · 0 comments
Open

LeetCode 236. Lowest Common Ancestor of a Binary Tree #25

Woodyiiiiiii opened this issue Apr 24, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

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原题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant