1. 程式人生 > >LeetCode刷題Medium篇Lowest Common Ancestor of a Binary Tree

LeetCode刷題Medium篇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 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.

十分鐘嘗試

之前做過一道尋找LCA的問題,不過當時是個二叉搜尋樹,左子樹都小於root,右子樹都大於root,可以利用(root.val-p.val)*(root.val-q.val)>0 尋找,如果不成立,則沒有公共祖先。

https://blog.csdn.net/hanruikai/article/details/85000183

上面的方法僅僅適用於二叉搜尋樹,因為有序性。這個二叉樹,我們可以利用直覺的方法。如果尋找p和q的LCA,首先想到的是遍歷二叉樹找到p和q,在尋找的過程中,儲存所有的父親節點到有序集合(倒序)----stack,然後比較兩個集合,第一個相同的元素就是LCA。

迭代的方案比較繁瑣,看了看思路提示,可以用遞迴方法解決,類似於之前的方法,雖然不能根據乘積判斷在那側,但是可以遞迴尋找pq節點。判斷兩個節點在那側。

/**
 * 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||root==p||root==q){
            //假如3個節點,返回是root.left 或者root.right
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
            //pq分別在左右子樹發現,返回root就是公共祖先
            return root;
        }
        if(left==null&&right==null){
            //不存在公共祖先
            return null;
        }
        //左子樹或者右子樹集中存在pq,不是分佈在兩側,也不是不存在pq節點
        return left==null?right:left;
    }
}