3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)

Posted juanqiuxiaoxiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)相关的知识,希望对你有一定的参考价值。

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /                  ___5__          ___1__
   /      \        /         6      _2       0       8
         /           7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {   
        if(root == null){
            return null;
        }
        if(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 left;
        }
        if(right != null){
            return right;
        }
        return null;
    }
}

这道题在235基础上取消了BST的限制,所以我们无法通过比较值的大小来进行剪枝,那么这道题的思路就是用一般的recursion来做。

明确一点,如果某个顶点是我们所要的结果,则有且只有一种情况满足条件:该node左树,右树,分别有p,q之一。(*)

某个node左树(或右树)有p 和 q,则这个node一定不是最小公共node。

基于此,我们的recursion就写出来啦

1.base case: null

2. subproblem: 左树,右树

2.recursion rule: 如果看到了p,q,返回。否则调用subproblem。

如果左右都不是null,说明左右各有一p,q,满足(*),返回当前root

如果左不为空,返回左

如果右不为空,返回右

 

 

 

 

以上是关于3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc

1143 Lowest Common Ancestor

1143 Lowest Common Ancestor

1143. Lowest Common Ancestor (30)

Lowest Common Ancestor III

A1143. Lowest Common Ancestor