1. 程式人生 > >[LeetCode] Lowest Common Ancestor of a Binary Tree 二叉樹的最小共同父節點

[LeetCode] 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]

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         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 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.

這道求二叉樹的最小共同父節點的題是之前那道 Lowest Common Ancestor of a Binary Search Tree 的Follow Up。跟之前那題不同的地方是,這道題是普通是二叉樹,不是二叉搜尋樹,所以就不能利用其特有的性質,所以我們只能在二叉樹中來搜尋p和q,然後從路徑中找到最後一個相同的節點即為父節點,我們可以用遞迴來實現,在遞迴函式中,我們首先看當前結點是否為空,若為空則直接返回空,若為p或q中的任意一個,也直接返回當前結點。否則的話就對其左右子結點分別呼叫遞迴函式,由於這道題限制了p和q一定都在二叉樹中存在,那麼如果當前結點不等於p或q,p和q要麼分別位於左右子樹中,要麼同時位於左子樹,或者同時位於右子樹,那麼我們分別來討論:

若p和q要麼分別位於左右子樹中,那麼對左右子結點呼叫遞迴函式,會分別返回p和q結點的位置,而當前結點正好就是p和q的最小共同父結點,直接返回當前結點即可,這就是題目中的例子1的情況。

若p和q同時位於左子樹,這裡有兩種情況,一種情況是left會返回p和q中較高的那個位置,而right會返回空,所以我們最終返回非空的left即可,這就是題目中的例子2的情況。還有一種情況是會返回p和q的最小父結點,就是說當前結點的左子樹中的某個結點才是p和q的最小父結點,會被返回。

若p和q同時位於右子樹,同樣這裡有兩種情況,一種情況是right會返回p和q中較高的那個位置,而left會返回空,所以我們最終返回非空的right即可,還有一種情況是會返回p和q的最小父結點,就是說當前結點的右子樹中的某個結點才是p和q的最小父結點,會被返回,寫法很簡潔,程式碼如下:

解法一:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
       if (!root || p == root || q == root) return root;
       TreeNode *left = lowestCommonAncestor(root->left, p, q);
       TreeNode *right = lowestCommonAncestor(root->right, p , q);
       if (left && right) return root;
       return left ? left : right;
    }
};

上述程式碼可以進行優化一下,如果當前結點不為空,且既不是p也不是q,那麼根據上面的分析,p和q的位置就有三種情況,p和q要麼分別位於左右子樹中,要麼同時位於左子樹,或者同時位於右子樹。我們需要優化的情況就是當p和q同時為於左子樹或右子樹中,而且返回的結點並不是p或q,那麼就是p和q的最小父結點了,已經求出來了,就不用再對右結點呼叫遞迴函數了,參見程式碼如下:

解法二:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
       if (!root || p == root || q == root) return root;
       TreeNode *left = lowestCommonAncestor(root->left, p, q);
       if (left && left != p && left != q) return left;
       TreeNode *right = lowestCommonAncestor(root->right, p , q);
    if (left && right) return root; return left ? left : right; } };

此題還有一種情況,題目中沒有明確說明p和q是否是樹中的節點,如果不是,應該返回NULL,而上面的方法就不正確了,對於這種情況請參見 Cracking the Coding Interview 5th Edition 的第233-234頁。

類似題目:

參考資料: