Lowest Common Ancestor of a Binary Tree

題目描述:node

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.學習

題目分析:spa

首先,題目給出的是一個二叉樹,同時給定兩個節點,要求尋找兩個節點的最低公共祖先(能夠爲兩節點)。也就是說目標節點的左右子樹分別包含兩個節點,或者是節點自己。code

解題思路:blog

節點a與節點b的公共祖先c必定知足:a與b分別出如今c的左右子樹上(若是a或者b自己不是祖先的話)。首先想到的是遞歸孫發,分別在根節點的左子樹和右子樹進行尋找,找到兩節點,返回當前節點,沒有找到則返回空。若根節點的左右子樹找到了兩節點,該節點就是所找的LCA。遞歸

代碼:ip

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

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

爲了讓讀者更容易明白此算法,下面舉個例子進行分析:博客

尋找6,4的LCA

第一步:

根節點3,不是所找節點,進入3的左右子樹5,1尋找。

第二步:

根節點5,不是所找節點,進入5的左右節點6,2尋找;

根節點1,不是所找節點,進入1的左右節點0,8尋找。

第三步:

根節點6,是所找節點,返回此節點;

根節點2,不是所找節點,進入2的左右節點7,4尋找;

根節點0,8,不是所找節點,返回NULL。

第四步:

根節點7,不是所找節點,返回NULL。

根節點4,是所找節點,返回此節點;

第五步:

返回L = 6,R= 2,返回root = 5,找到結果。

 

分析一下此算法的複雜度,最壞的狀況,也就是每一個節點都須要進行檢查,時間複雜大爲O(n),空間複雜的爲O(1)。

遞歸算法優勢是思路很清晰,代碼很是簡潔,缺點是,在尋找的兩個節點處於較深的位置時,須要屢次壓棧迭代,算法複雜度較高。

此博客中的內容均爲原創或來自網絡,不用作任何商業用途。歡迎與我交流學習,個人郵箱是lsa0924@163.com

相關文章
相關標籤/搜索